I'm trying to figure out what's not working here in my jQuery..
HTML
<ul>
<div class="filter-all">
<div class="filter-select-all">Select All</div> |
<div class="filter-select-none">Select None</div>
</div>
<li><label><input type="checkbox">Food</label></li>
<li><label><input type="checkbox">Meeting</label></li>
<li><label><input type="checkbox">Music</label></li>
<li><label><input type="checkbox">Outdoors</label></li>
</ul>
jQuery
$('.filter-select-all').click(function() {
$(this).closest('ul').find(':checkbox').attr('checked', this.checked);
});
Demo: http://jsfiddle.net/MDNmx/
I've tried all kinds of different methods instead of closest and find too..
Thanks for any help :)
jsFiddle Demo
$(function() {
$('.filter-select-all').click(function() {
$(this).closest('ul').find('input[type="checkbox"]').prop('checked', true);
});
});
Update:
FYI -- the HTML specification says that only <li>
should be a direct descendant of <ul>
, so you should change your HTML to look like:
<div class="filter-all">
...
</div>
<ul id='checkboxes'> ... </ul>
Then your code will look like:
$(function () {
$('.filter-select-all').click(function () {
$('#checkboxes').find('input[type="checkbox"]')
.prop('checked', true);
});
$('.filter-select-none').click(function () {
$('#checkboxes').find('input[type="checkbox"]')
.prop('checked', false);
});
});
Further update: (demo)
To condense the two click handlers into one, consider updating your HTML further (split filter-select-all
into filter-select
and all
):
<div class="filter-all">
<div class="filter-select all">Select All</div>|
<div class="filter-select none">Select None</div>
</div>
Then you can use the second class for the boolean flip:
$(function () {
$('.filter-select').click(function () {
$('#checkboxes').find('input[type="checkbox"]')
.prop('checked', $(this).is('.all'));
});
});
$('.filter-select-all').click(function() {
$(this).parent().siblings('li').children().find('input[type="checkbox"]').prop("checked",true);
});
$('.filter-select-none').click(function() {
$(this).parent().siblings('li').children().find('input[type="checkbox"]').prop("checked",false);
});
$('.filter-select-all').click(function() {
$(this).closest('ul').find('input:checkbox').prop('checked', true);
});
Add a "class" attribute on each checkbox :
< li>< label>< input class='check' type="checkbox">Food< /label>< /li>
write javascript as follows:
$('.filter-select-all').click(function() {
$('.check').each(function(k,v) {
v.checked = true;
}); });
$('.filter-select-none').click(function() {
$('.check').each(function(k,v) {
v.checked = false;
}); });