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=neighborhood_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?