Shawn Mclean
Shawn Mclean

Reputation: 57469

Jquery check list of elements for a match

I have some checkboxes grouped using the attribute rel. When anyone is unchecked, I want to check if all are also unchecked, then do something.

Scenario: I have a parent checkbox that is all of the children are unchecked, the parent should be. If one or more is checked, the parent needs to be checked.

All child checkboxes have the class name child.

$('.child').change(function () {
   var groupdId = $(this).attr('rel');
   if($('.child').where('rel', groupId).any('checked', true)) <-- how do I do this?
   {
       //Uncheck the parent
   }
   else {
       //Check the parent.
   }
});

What I attempted here is: for elements with class .child AND rel == groupdId, if any of them are checked, do x.

Upvotes: 0

Views: 150

Answers (2)

Chad Moran
Chad Moran

Reputation: 12854

$('.child[rel="' + groupId + '"']:checked').length > 0

[rel=...] is a way to select against an attribute http://api.jquery.com/attribute-equals-selector/

:checked is a jQuery psuedo-selector http://api.jquery.com/checked-selector/

var checkbox = $('.child[rel="' + groupId + '"']');
checkbox.prop('checked', !checkbox.is(':checked'));

Upvotes: 1

simshaun
simshaun

Reputation: 21466

Untested, but I think this will work.

var $boxes = $('input.child');

$boxes.click(function() {
    var $box = $(this),
        grp = $box.attr('rel'),
        $boxes_in_group = $boxes.filter("[rel='"+ grp +"']");

    if ( $box[0].checked )
        // Check the parent.
    else if ( $boxes_in_group.filter(":checked").length == 0 )
        // Uncheck the parent.
});

Upvotes: 0

Related Questions