简体   繁体   中英

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?

<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. If you find one that is checked you can set that variable to true and break out of the loop.

Iterate the inputs, and +1 increment a variable for every checked instance, and if the counter is 0, throw an error.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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