[英]set of radio button validation using Javascript
I am trying to validate 2 sets of radio button using Javascript. 我正在尝试使用JavaScript验证2套单选按钮。 It is working with one set but not when I add another radio set (secondtime visitor).
它可以使用一个收音机,但是不能添加另一个收音机(第二位访问者)。 Here is my code:
这是我的代码:
HTML: HTML:
<form name="form1" action="#" method="post">
First time visitor?:<br/>
<label for="s1">Yes</label>
<input type="radio" id="radio1" name="firsttime" value="1"/>
<br/>
<label for="s2">No</label>
<input type="radio" id="radio2" name="firsttime" value="2"/>
<br/>
Second time visitor?:<br/>
<label for="s1">Yes</label>
<input type="radio" id="radio1" name="secondTime" value="1"/>
<br/>
<label for="s2">No</label>
<input type="radio" id="radio2" name="secondTime" value="2"/>
<br/>
<button type="submit" name="nextBTN" onclick="return validateForm();">Next</button><br/>
</form>
And Javascript code: 和Javascript代码:
function validateForm() {
var radios = document.getElementsByName("firsttime");
var radios2 = document.getElementsByName("secondtime");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
var j = 0;
while (!formValid && i < radios2.length) {
if (radios2[j].checked) formValid = true;
j++;
}
if (!formValid) alert("Must check some option!");
return formValid;
}
At first glance, I can see that in your second while loop, you still check the radios
variable instead of the radios2
variable. 乍一看,我可以看到在您的第二个while循环中,您仍然检查
radios
变量而不是radios2
变量。
You also used the i
variable instead of j
in the second loop. 在第二个循环中,您还使用了
i
变量而不是j
。 And you weren't consistent with the capitalization of secondTime
(vs secondtime
). 而且您与
secondTime
(vs secondtime
)的大小写secondtime
。
Here's a working version of your code: http://jsfiddle.net/8edCn/ 这是您的代码的有效版本: http : //jsfiddle.net/8edCn/
EDIT: Updated version per your comment: http://jsfiddle.net/8edCn/2/ 编辑:根据您的评论更新的版本: http : //jsfiddle.net/8edCn/2/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.