I have two checkboxes and one of the checkboxes must be checked. I can see that it’s right, no syntax errors. What should be made to my code to check if none of the checkboxes were checked?
HTML :
<input type="checkbox" value="aa" class="first" name="a"> Yes<br/>
<input type="checkbox" value="bb" class="second" name="b"> No <br/>
<button type="submit">Go!</button>
<p class="error"></p>
JavaScript:
$('button').on('click',function(){
if( $(".first:not(:checked)") && $(".second:not(:checked)") ){
$('.error').text('You must select atleast one!');
}else
$('.error').hide();
});
Example : http://jsfiddle.net/ptbTq/
You are using selectors which do not return boolean values which is what you need when writing an
ifcondition. Here’s what you could do:or if you prefer and think it could be more readable you could invert the condiciton:
Also notice that you need to
.show()the error message in the first case as you are hiding it in the second.And here’s a live demo.