Reputation: 89
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.
Upvotes: 0
Views: 100
Reputation: 39
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/
Upvotes: -1
Reputation: 22405
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++;
}
Upvotes: 0
Reputation: 3196
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.
Upvotes: 0
Reputation: 11963
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.
Upvotes: 0