Home:ALL Converter>Checkbox JavaScript Validation

Checkbox JavaScript Validation

Ask Time:2014-11-08T05:16:13         Author:Danielle Stewart

Json Formatter

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.

Author:Danielle Stewart,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/26810228/checkbox-javascript-validation
CaldwellYSR :

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.",
2014-11-07T21:21:41
Sterling Archer :

Iterate the inputs, and +1 increment a variable for every checked instance, and if the counter is 0, throw an error.\n\nvar check = 0;\nArray.prototype.forEach(document.querySelectorAll(\"input[name='dare']\"), function(x) {\n if (x.checked) check++;\n});\nif (!check) //error\n\n\nFaster but prone to more issues but simpler to understand for loop variation:\n\nvar x = document.querySelectorAll(\"input[name='dare']\");\nfor (var i=0; i<x.length; i++) {\n if (x[i].checked) check++;\n}\n",
2014-11-07T21:22:36
Steve :

you assign a common class to all the checkbox inputs, and then on submit event you iterate thru all the checkboxes with that class to see if any of them is checked. ",
2014-11-07T21:21:31
yy