简体   繁体   English

复选框JavaScript验证

[英]Checkbox JavaScript Validation

I'm working on validating the following code so that onsubmit, the user should have selected at least one checkbox. 我正在验证以下代码,以便在提交时,用户应至少选择一个复选框。 How would I validate the following checkboxes in JavaScript? 如何验证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>

Some of the other validation codes that have been shared on this forum doesn't work for me. 在这个论坛上共享的其他一些验证代码对我不起作用。

您为所有复选框输入分配了一个通用类,然后在提交事件时,遍历该类的所有复选框以查看是否选中了其中的任何一个。

The way I would validate something like this would be to set a variable to false and loop through all of the options checking to see if they are checked. 我将验证此类内容的方法是将变量设置为false并循环检查所有选项以查看是否已选中它们。 If you find one that is checked you can set that variable to true and break out of the loop. 如果找到一个被选中的变量,则可以将该变量设置为true并退出循环。

Iterate the inputs, and +1 increment a variable for every checked instance, and if the counter is 0, throw an error. 迭代输入,并为每个检查的实例+1递增一个变量,如果计数器为0,则抛出错误。

var check = 0;
Array.prototype.forEach(document.querySelectorAll("input[name='dare']"), function(x) {
    if (x.checked) check++;
});
if (!check) //error

Faster but prone to more issues but simpler to understand for loop variation: 更快,但容易出现更多问题,但对于循环变化更易于理解:

var x = document.querySelectorAll("input[name='dare']");
for (var i=0; i<x.length; i++) {
    if (x[i].checked) check++;
}
if($("input:checkbox[name='dare']:checked").length >0)
 { 
    console.log("Atleast One checkbox selected");
 }else {
    console.log("nothing selected");
  }

You may find working code here - http://jsfiddle.net/spnfpkxz/ 您可以在这里找到工作代码-http: //jsfiddle.net/spnfpkxz/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM