多组单选按钮验证javascript


multiple grouped radio button validation javascript

我有多个分组单选按钮,按名称optionRadios1到5。我想通过javascript验证它们,但我的验证代码不工作,仍然继续提交表单。

下面是我的代码:
function submitForm(){
var counter = "<?php echo $count;?>"; //$count is the total number of grouped radio buttons
for(j=1;j<=counter;j++) {   
        var radioname = "optionRadios" + j;
        var elem=document.forms['test-form'].elements[radioname];
        len=elem.length-1;
        chkvalue='';
        for(i=0; i<=len; i++){
            if(elem[i].checked){chkvalue=elem[i].value;}
        }
        if(chkvalue=='') {
            alert('There are still unanswered questions. ' + radioname);
        return false;
        }else {
         $('#test-form').submit();
        }
    }
}

这是它应该被使用的形式:

<form action="#" method="post" id="test-form">
//lots of codes here
<button type="submit" class="btn btn-primary" onclick="return submitForm();" id="next">Next</button>

</form>

试试这个

$('#test-form').submit(function() {
    var counter = "<?php echo $count;?>"; //$count is the total number of grouped radio buttons
    console.log("Counter: "+counter);
    for(j=1;j<=counter;j++) {   
        var radioname = "optionRadios" + j;
        console.log("RadioName: "+radioname);
        var elem=document.forms['test-form'].elements[radioname];
        len=elem.length-1;
        chkvalue='';
        console.log("Length: "+len);
        for(i=0; i<=len; i++){
            if(elem[i].checked){chkvalue=elem[i].value;}
        }
        console.log("Chkvalue: "+chkvalue);
        if(chkvalue=='') {
            alert('There are still unanswered questions. ' + radioname);
            return false;
        }
    }
    return true;
});

从按钮中删除onclick属性,并查看正在调试的值。它将帮助您查看代码在哪里工作,在哪里不工作。尝试一下,让我们知道控制台的输出。

JAVASCRIPT

$('input[type=button]').click(function(){
var i= 1 ;
var msgError= "";
while($('input[name=optionRadios'+i+']').length ){
    var is_it_ok = false;
    $('input[name=optionRadios'+i+']').each(function(){
        if($(this).is(":checked")){
            is_it_ok = true;
        }
    });
    if(!is_it_ok){
        msgError += "Erreur : optionRadios"+i; 
    }
    i++;
}
if(!msgError.length){
       alert("ok");
    return true;
}else{
    alert(msgError);
    return false;
}
});
              });
HTML

<form name="test-form">
<input type="radio" name="optionRadios1" value="1" />
<input type="radio" name="optionRadios1" value="1"/>
<input type="radio" name="optionRadios1" value="1"/>
<input type="radio" name="optionRadios2" value="1"/>
<input type="radio" name="optionRadios2" value="1"/>
<input type="radio" name="optionRadios2" value="1"/>
<input type="button" />
</form>
DEMO: http://jsfiddle.net/VZHGJ/

您尝试过使用jQuery验证方法吗?http://jqueryvalidation.org/documentation/