JQuery - Checkbox stays proven - simple filtering system

I am creating a very simple filter system where I want to have html checkboxes that can show and hide elements of certain categories.

The problem is that the checkboxes remain checked no matter what.

Jsfiddle example: 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 saw two posts on this topic, but I'm not sure if they are completely related or why my code in particular does not work. I also tried using the preventdefault function, but did nothing:

Cannot control flag status - jquery Why won't the .attr ('checked', 'checked') parameter be set?

Any help is always appreciated, thanks!

+1
source share
5 answers

It is blocked by preventDefault() . Take a look at this: http://jsfiddle.net/q8bAE/5/ You can see that the second flag is functioning normally, while the first remains in its original state when clicked.

It seems that preventDefault() is stopping checkbox actions that I have not known so far! The docs for toggle() say: "the implementation also calls .preventDefault () for the event"

+5
source

I'm not quite sure why you get an error when you do it this way, but changing the code to use "change" fixes it.

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

+2
source

Here's another solution, dynamically capturing a category from a checkbox value.

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

0
source

I never liked using removeAttr with checked ... try leaving this ( DEMO ). This is even less code.

0
source

.toggle() intended to show / hide this element.

Here is my solution: http://jsfiddle.net/pBKbz/

0
source

Source: https://habr.com/ru/post/905571/


All Articles