复选框JavaScript验证

时间:2014-11-07 21:16:14

标签: javascript html html5 validation

我正在验证以下代码,以便onsubmit,用户应该至少选中一个复选框。我如何在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>

此论坛上分享的其他一些验证码对我来说并不起作用。

4 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我验证这样的事情的方法是将变量设置为false并循环遍历所有选项以检查它们是否被检查。如果找到一个被检查的,你可以将该变量设置为true并跳出循环。

答案 2 :(得分:0)

迭代输入,+ 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++;
}

答案 3 :(得分:-1)

if($("input:checkbox[name='dare']:checked").length >0)
 { 
    console.log("Atleast One checkbox selected");
 }else {
    console.log("nothing selected");
  }

您可以在此处找到工作代码 - http://jsfiddle.net/spnfpkxz/

相关问题