开发者

Jquery - Checkbox staying checked - simple filter system

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 entire开发者_高级运维ly 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 for toggle() say "the implementation also calls .preventDefault() on the event"


Im not totally sure why you get the error when doing it that way, but changing the code to use 'change' fixes it..

http://jsfiddle.net/Jmnwr/13/


Here's yet another solution, dynamically grabbing the category from the checkbox value.

http://jsfiddle.net/csaltyj/Jmnwr/17/


I never liked using removeAttr with checked... try leaving that out (DEMO). It's even less code.


.toggle() is intended to show/hide the element in question.

Here's my solution: http://jsfiddle.net/pBKbz/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜