I am building a very simple filter system where I want to have html checkboxes that can show and hide items of particular categories.
The problem is that the checkboxes stay checked no matter what.
Example on jsfiddle: http://jsfiddle.net/Jmnwr/
HTML:
<ul id="filters">
<li><input type="checkbox" checked="checked" value="categorya" id="filter-categorya" /><label for="filter-categorya">Category A</label></li>
<li><input type="checkbox" checked="checked" value="categoryb" id="filter-categoryb" /><label for="filter-categoryb">Category B</label></li>
</ul>
<div class="categorya"></div>
<div class="categorya"></div>
<div class="categorya"></div>
<div class="categorya"></div>
<div class="categoryb"></div>
<div class="categoryb"></div>
<div class="categoryb"></div>
JS:
$("#filter-categorya").toggle(
function() {
$('.categorya').stop().fadeTo('slow', 0.2);
$('#filter-categorya').removeAttr('checked');
}, function() {
$('.categorya').stop().fadeTo('slow', 1.0);
$('#filter-categorya').attr('checked', 'checked');
});
$("#filter-categoryb").toggle(
function() {
$('.categoryb').stop().fadeTo('slow', 0.2);
$('#filter-categoryb').removeAttr('checked');
}, function() {
$('.categoryb').stop().fadeTo('slow', 1.0);
$('#filter-categoryb').attr('checked', 'checked');
});
I have seen two posts regarding this topic but not sure if they are entirely related or why my code in particular is not working. I’ve also tried using the preventdefault function but it didn’t do anything:
Unable to control checkbox checked status – jquery
Why won't .attr('checked','checked') set?
Any help always appreciated,
Thanks!
It’s being blocked by
preventDefault(). Take a look at this: http://jsfiddle.net/q8bAE/5/ You can see that the 2nd checkbox functions normally, while the first remains in its initial state when clicked.It appears that
preventDefault()causes checkbox change actions to be stopped… which I didn’t know until right now! The docs fortoggle()say “the implementation also calls .preventDefault() on the event”