Using jQuery to Validate A Required Selection with Checkboxes

I have a form with two sets of check boxes. I need to validate a selection from each set has been made before I allow a submit. jQuery has a handful of selectors to help you easily get a hold of elements.
The common approach is to treat the check boxes as a single object, and traverse through each node using the .each() method. But I wanted to find a simple one-line approach I could re-use for each set.

Typical Approach (single set of check boxes)

$("input[@type=checkbox][@checked]").each(
function() {}
);

That’s not going to work if you have two sets of check boxes on the form with different names.






Don’t make the mistake of using the ID as a selector:
$(‘#fieldId:checked’)
It will limit you to the first element of the set.

To validate a required selection has been made, we’ll select the check boxes we need by selecting the checked ones by name, and counting the size(nodes) of the object. From there the logic is in your hands. In this example, I am checking to see if at least one has been checked in either set.


if($('input[@name=fieldName]:checked').size() == 0){
alert('Please Make A Selection for fieldName');
}else if($('input[@name=fieldNames]:checked').size() == 0){
alert('Please Make A Selection for fieldNames');
}

UPDATE

JQuery 1.3+ no longer supports the ‘@’ syntax.

The above code would then be:

if($('input[name=fieldName]:checked').size() == 0){
alert('Please Make A Selection for fieldName');
}else if($('input[name=fieldNames]:checked').size() == 0){
alert('Please Make A Selection for fieldNames');
}

Leave a Reply

Your email address will not be published. Required fields are marked *