gpt4 book ai didi

javascript - 检查我的所有单选按钮是否已填充

转载 作者:行者123 更新时间:2023-12-02 18:05:19 24 4
gpt4 key购买 nike

我需要弄清楚如何检查我的单选按钮是否已全部填充。这就是我所拥有的,但它只检查一个按钮

    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">

感谢任何帮助。

最佳答案

试试这个:

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;

Fiddle

关于javascript - 检查我的所有单选按钮是否已填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20154478/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com