Mackelito
Mackelito

Reputation: 4421

jQuery select/unselect all but only within the same element

I have the code working but when I add yet another ul it selects all checkboxes.

$('#checkall').click(
function(){
    $(this).closest('ul').find(':checkbox').attr('checked', this.checked);
    $(this).closest('ul').find('span').toggleClass('checked', this.checked)
})

<div class="checks">
 <ul>
  <li><label for="checkall"><div class="checker"><span class=""><input type="checkbox"  id="checkall" name="about"></span></div><strong>About our program</strong></label></li>
  <li><label for="about1"><div class="checker"><span><input type="checkbox" id="about1" name="about"></span></div>CEO Message</label></li>
 </ul>
</div>

Upvotes: 1

Views: 624

Answers (2)

c4urself
c4urself

Reputation: 4287

Just use your div with class checks:

$("#checkall").click(function() {
     $(this).closest("div.checks").find(":checkbox").attr("checked", this.checked);
     $(this).closest("div.checks").toggleClass("checked", this.checked);
});

Update

Since you want multiple checkall input's, you're going to want to use a class instead of an id. So make #checkall => input.checkall and it should work.

See my fiddle: http://jsfiddle.net/c4urself/jvPR3/

Upvotes: 2

artwl
artwl

Reputation: 3582

you can use:

$('#checkall').click(
function(){
    $(this).find(':checkbox').attr('checked', this.checked);
    $(this).find('span').toggleClass('checked', this.checked)
})

<div class="checks">
 <ul>
  <li><label for="checkall"><div class="checker"><span class=""><input type="checkbox"  id="checkall" name="about"></span></div><strong>About our program</strong></label></li>
  <li><label for="about1"><div class="checker"><span><input type="checkbox" id="about1" name="about"></span></div>CEO Message</label></li>
 </ul>
</div>

Upvotes: 1

Related Questions