我有多个分组的单选按钮,名称为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>
答案 0 :(得分:2)
试试这个
$('#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属性,然后查看正在调试的值。它可以帮助您查看代码的位置并且无法正常工作。试试看,让我们知道控制台输出的内容。
答案 1 :(得分:2)
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>
答案 2 :(得分:0)
您是否尝试过使用jQuery验证方法? http://jqueryvalidation.org/documentation/