jQuery: Multiple Checkbox Validation

Posted by Jetlogs @ 11:52 am
Category: Web Development, jQuery

Having problems with checkbox validations? Then you’re not alone. Checkbox validation is usually more difficult due to its nature of having multiple values at the same time.

Consider this simple form where a user is required to select at least one checkbox:
Which of the following jQuery selectors do you usually use?
(Please select at least one)

#id

.class

element[@attribute]

Which of the following jQuery events do you usually encounter?
(Please select at least one)

click

focus

change

blur

submit

<b>Which of the following jQuery selectors
do you usually use? (Please select at least one)</b><br>
<input type="checkbox" name="selector[]"
id="selector" value="id">#id<br>
<input type="checkbox" name="selector[]"
id="selector" value="class">.class<br>
<input type="checkbox" name="selector[]"
id="selector" value="element">element[@attribute]<br><br>

<b>Which of the following jQuery events
do you usually encounter? (Please select at least one)</b><br>
<input type="checkbox" name="event[]"
id="event" value="click">click<br>
<input type="checkbox" name="event[]"
id="event" value="focus">focus<br>
<input type="checkbox" name="event[]"
id="event" value="change">change<br>
<input type="checkbox" name="event[]"
id="event" value="blur">blur<br>
<input type="checkbox" name="event[]"
id="event" value="submit">submit<br>

So how do we do the validation?

First we’ll have to bind the validations with the form’s submit event (submit() event on jQuery) and return false for all empty checkbox groups to prevent the form triggering its submission.

Without using jQuery, you’ll have to iterate through all of the checkbox elements, then check for the checked status of each individual check boxes (if none is checked then return false). And you’ll have to do this for each check box grouping.

However, jQuery makes things a little bit easier by introducing a selector filter for checked elements.
Using the :checked filter, it will select all of the checked elements for a particular element. so in this case,

$("input:checked")

will select all of the checked input elements. However, this is a downside for this. The :checked filter does not support #id and .class selectors so the following won’t work:

$("#selector:checked")
$("#event:checked")

So how do we work around this? Its pretty simple, by specifying the id, class, or even as an attribute, we can now separate the checkboxes according to its grouping. In this example, we are going to be using the #id to separate our checkboxes.

var selector_checked = $("input[@id=selector]:checked").length;
var event_checked = $("input[@id=event]:checked").length;
if (selector_checked == 0)
{
	return false;
}
else if (selector_checked == 0)
{
	return false;
}
else
{
	return true;
}

Its much simpler than iterating through each checkbox, since jQuery automatically does this for us. For two different checkbox groups, this is acceptable. However, when we would need to deal with more checkbox groupings, this can become a problem since the code will become more cluttered by then.

To simplify things, we’ll just make our own function passing the #id as a parameter to check for each checkbox group’s status. This is how the script would finally look like.

$(document).ready(function()
{
	$("form").submit(function()
	{
		if (!isCheckedById("selector"))
		{
			alert ("Please select at least one selector");
			return false;
		}
		else if (!isCheckedById("event"))
		{
			alert ("Please select at least one event");
			return false;
		}
		else
		{
			return true; //submit the form
		}
	});

	function isCheckedById(id)
	{
		var checked = $("input[@id="+id+"]:checked").length;
		if (checked == 0)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
});

10 Comments »

10 Comments to “jQuery: Multiple Checkbox Validation”

  1. Trey
    1

    Nice work. I’m looking for a method that will keep the name=”" fields different. The perl script needs the name value.

  2. Gemtag
    2

    Thanks for the solution. I was pulling my hair out trying to figure out why using the id selector wouldn’t work.

  3. Jetlogs
    3
    Author Comment

    @Trey:

    If you want to use the names instead, use the following function:

    function isCheckedByName(inputName)
    {
        var checked = $("input[name="+inputName+"]:checked").length;
        if (checked == 0)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
  4. pinginbisa
    4

    with this code, how to use validation with radio type or checkbox type.

  5. Luigi Zambetti
    5

    Hi,
    how can you validate a textbox that must be valorized if a particular checkbox value is checked?
    For example, if I have:

    #id
    .class
    other

    I want that “other” has a value when the user select “other” checkbox value.

    Thanks a lot.

    Luigi

  6. Jetlogs
    6
    Author Comment

    @Luigi:

    <input type="checkbox" name="other" id="other">
    <input type="text" name="otherValue" id="otherValue" >

    Then just validate to see if #other is checked
    if it is, get the value of #otherValue textbox

  7. Luigi Zambetti
    7

    I’ve tried this way to validate a checkbox if at least one checkbox is selected:

    myTextbox: {
    required: (‘#myFirstCheckbox:checked’ || ‘#mySecondCheckbox:checked’)
    },

    but doesn’t work.
    How can I solve?

    L

  8. Hans Grimm
    8

    multiple use of the same ID will generate HTML validation errors. will try the names solution above.

  9. siddu
    9

    $(‘#divid input[type=checkbox]:checked’).length
    This will work fine if you put the group checkboxes in a separate “div”

  10. Icesnake
    10

    @Luigi

    You can validate the way you’re requesting using a jQuery statement such as this:

    function myValidate(){
    if( ($(‘#other:checked’).length > 0) && ($(‘#otherValue’).val().length > 0) ){ //check to see if the box is checked by using the :checked selector, then if that’s true, check to see if there is a value set on the text box
    //stuff to do if the box is checked and the person entered information into the text box
    }
    }

RSS Comment Feed Comments RSS |trackback TrackBack URI

Leave a comment

  • Archives

  • Donations

  • Social Bookmarks

  • Jetlogs.org
    Some Rights Reserved 2007
    Creative Commons License