jQuery Failure to Uncheck Checkboxes Programmatically
Simple functionality, I want to toggle checking/unchecking checkboxes based on changing a top level checkbox.
The problem is that Toggle/Click event handlers have inherent issues. If you try to bind these handlers to an input checkbox, the default checking behavior of the box fails.
So, I tried to use the Change handler in one of two different ways.
$('input.all_neighborhoods').change(function(){
if($(this).not(':checked')){
$(this).closest('li').siblings('li').find('input[name=neighborhood_id]').attr('checked','checked');
}
else{
$(this).closest('li').siblings('li').find('input[name=neighborhood_id]').removeAttr('checked');
}
});
Here, the first change works as you'd expect. All sibling checkboxes are selected and checked. However, when I click again to uncheck, nothing happens. The event handler doesn't work.
I then tried this:
$('input.all_neighborhoods').change(function(){
$(this).attr( 'checked', $(this).is( ':checked' ) ? $(this).closest('li').siblings('li').find('input[name=n开发者_运维知识库eighborhood_id]').attr('checked','checked'): $(this).removeAttr('checked').closest('li').siblings('li').find('input[name=neighborhood_id]').removeAttr('checked') );
});
Here, the sibling checkboxes effectively toggle. However, the main on/off switch checkbox stays checked.
Is the issue here related to the fact that they are all siblings and the main checkbox is not the parent?
(Warning, shameless self-promotion ahead). I've written a jQuery plugin that handles all of this messiness for you. No need to reinvent the wheel.
Check it out: http://mjball.github.com/jQuery-CheckAll/
If you want to stick with your current method, here's how to fix it:
$('input.all_neighborhoods').change(function() {
$(this).closest('li')
.siblings('li')
.find('input[name=neighborhood_id]').attr('checked', this.checked);
}
Just pass a boolean to .attr()
. Also, as per When to use Vanilla JavaScript vs. jQuery? don't use
$(this).is(':checked')
Instead use
this.checked
It's fewer characters to write, doesn't require any jQuery, and is way more efficient.
精彩评论