复选框JavaScript验证

复选框JavaScript验证,javascript,html,validation,Javascript,Html,Validation,我正在验证以下代码,以便在提交时,用户应该至少选中一个复选框。如何在JavaScript中验证以下复选框 <input type="checkbox" name="dare" value="q1"/> I dare you to say the alphabet backwards <br> <input type="checkbox" name="dare" value="q2"/> I dare you to go to a random pers

我正在验证以下代码,以便在提交时,用户应该至少选中一个复选框。如何在JavaScript中验证以下复选框

<input type="checkbox" name="dare" value="q1"/> I dare you to say the alphabet backwards <br>

  <input type="checkbox"  name="dare" value="q2"/> I dare you to go to a random person and sing twinkle twinkle little star <br>

  <input type="checkbox" name="dare" value="q3"/> I dare you to act your true self for a day<br>

  <input type="checkbox" name="dare" value="q4"/> I dare you to not shower for a week <br>

  <input type="checkbox" name="dare" value="q5"/> I dare you to go vegetarian for 3 months<br>

  <input type="checkbox" name="dare" value="q6"/> I dare you to swim with dolphins <br>

  <input type="checkbox" name="dare" value="q7"/> I dare you to climb a mountain <br>

 <input type="checkbox" name="dare" value="q8"/> I dare you to not sleep for a day<br>

    <input type="checkbox" name="dare" value="q9"/> I dare you to walk backwards through the park <br>

    <input type="checkbox" name="dare" value="q10"/> I dare you to jump 50 times. <br>
你敢把字母表倒过来说
我敢让你去随便找一个人唱一闪一闪的小星星
我敢让你在一天内表现出真实的自我
我敢说你一个星期都不洗澡
我敢说你要吃素三个月
我敢让你和海豚一起游泳
我敢让你去爬山
我敢说你一天也睡不着觉
我敢让你在公园里向后走
我敢让你跳50次

在此论坛上共享的一些其他验证代码对我不起作用。

您为所有复选框输入分配了一个公共类,然后在提交事件中,您迭代该类的所有复选框,以查看是否选中了任何复选框

我验证类似内容的方法是将一个变量设置为false,并循环所有选项检查,以查看它们是否被检查。如果您找到一个选中的实例,您可以将该变量设置为true并中断循环。

迭代输入,并为每个选中的实例+1递增一个变量,如果计数器为0,则抛出一个错误

var check = 0;
Array.prototype.forEach(document.querySelectorAll("input[name='dare']"), function(x) {
    if (x.checked) check++;
});
if (!check) //error
对于循环变化,速度更快但容易出现更多问题,但更易于理解:

var x = document.querySelectorAll("input[name='dare']");
for (var i=0; i<x.length; i++) {
    if (x[i].checked) check++;
}
var x=document.querySelectorAll(“input[name='dare']”);
对于(var i=0;i

您可以在此处找到工作代码-

您提到其他验证代码对您不起作用。您可以提供您尝试的代码吗?为什么不在找到选中的实例时中断循环?可以,但这样可以消除深入验证的可能性。迭代所有选项不会降低页面速度,因此请加快速度这是一个没有实际意义的问题。@PranayKondekar不允许使用JQuery。我没有看到任何有问题的地方我不需要使用jQuery@PranayKondekar如果问题没有用jQuery标记,并且OP没有明确地说“jQuery答案很好”,则假定不需要使用jQuery库
if($("input:checkbox[name='dare']:checked").length >0)
 { 
    console.log("Atleast One checkbox selected");
 }else {
    console.log("nothing selected");
  }