keewee279
keewee279

Reputation: 1654

jQuery: Check / uncheck all siblings with certain class

I am new to jQuery and hope someone here can help me with this question.

I am trying to set up an "All" checkbox to check / uncheck all its sibling checkboxes (i.e. those under the same div / parent) - but only if they DO NOT have a certain class ("other").

My approach was to cause the least run time and to write this in a way that it can also be applied to similar structures in other divs.

The code I have works without the :not() selector but I can't get it to work when I include this. Also, I am not sure if my approach is the best / fastest way here.

My jQuery:

$('.checkAll').click(function(){
    if($(this).is(':checked')){
        $(this).siblings(":not($('.other'))").prop('checked', true);
    }else{
        $(this).siblings(":not($('.other'))").prop('checked', false);
    }
});

Many thanks in advance for any help, Mike

Upvotes: 0

Views: 3477

Answers (3)

Tushar
Tushar

Reputation: 87213

You don't need jQuery Selector inside :not.

$('.checkAll').on('click', function() {
    $(this).siblings(":not('.other')").prop('checked', $(this).is(':checked'));
});

$(this).is(':checked') returns true/false which you have checked using if and assigned the same to the checked.

Upvotes: 2

Balachandran
Balachandran

Reputation: 9637

remove jquery object in not selector ,you can use string

 $(this).siblings(":not('.other')").prop('checked', true);

Upvotes: 0

Adil
Adil

Reputation: 148150

You do not need $ within :not. You can optimize the code you using this.checked and avoid the if statement.

$('.checkAll').click(function(){
      $(this).siblings(":not('.other')").prop('checked', this.checked);
});

Upvotes: 2

Related Questions