我需要弄清楚如何检查我的单选按钮是否全部填满。这就是我所拥有的,但它只检查一个按钮
var btns = form.choice_1;
for (var i=0; el=btns[i]; i++) {
if (el.checked) return true;
}
alert('Please select a radio button');
return false;
这是我从中输入的表单。
<form onsubmit="return checkRadios(this);" name = "form" action = "like.php" method ="post" >
<h1> Questions </h1>
<p> Question 1 </p>
<input type="radio" name="choice_1" value="1">Like <input type="radio" name="choice_1" value="2" > Dislike
<p> Question 2 </p>
<input type="radio" name="choice_2" value="1">Like <input type="radio" name="choice_2" value="2" > Dislike
<p> Question 3 </p>
<input type="radio" name="choice_3" value="1">Like <input type="radio" name="choice_3" value="2" > Dislike
<p> Question 4 </p>
<input type="radio" name="choice_4" value="1">Like <input type="radio" name="choice_4" value="2" > Dislike
<br> <br>
<input type="submit" value="Submit">
感谢任何帮助。
答案 0 :(得分:2)
试试这个:
var checkRadios = function () {
var btns = form.querySelectorAll('input[name^=choice_][type="radio"]');
for (var i = 0; i < btns.length; i = i + 2) {
var check = true;
if (!btns[i].checked && !btns[i + 1].checked) check = false;
}
if (!check) alert('Please select a radio button');
return check;
}
var form = document.querySelector('form[name="form"]');
form.onsubmit = checkRadios;
答案 1 :(得分:0)
你应该使用jQuery。它使它变得更容易。
你会这样做:
var e = ('#[[[[id of your radio]]]]');
if($e.is(':checked'){
//do what you need to
};
答案 2 :(得分:0)
试试这个。你需要jQuery。
checkRadios = function() {
if $("input:radio :checked").length == 0 {
alert('Please select a radio button');
return false;
}
}