Checkbox filtering using Jquery -
i'm using code: http://jsfiddle.net/6wyzw/42/ filter categories, need functionality different. if more 1 filter checked item contain both display.
example:
checking category , b display 'ab' not instances of 'a' , 'b'
html:
<ul id="filters"> <li> <input type="checkbox" value="categorya" id="filter-categorya" /> <label for="filter-categorya">category a</label> </li> <li> <input type="checkbox" value="categoryb" id="filter-categoryb" /> <label for="filter-categoryb">category b</label> </li>
<div class="item categorya categoryb">a, b</div> <div class="item categorya">a</div> <div class="item categorya">a</div> <div class="item categorya">a</div> <div class="item categoryb">b</div> <div class="item categoryb">b</div> <div class="item categoryb">b</div>
js:
$("#filters :checkbox").click(function() { var re = new regexp($("#filters :checkbox:checked").map(function() { return this.value; }).get().join("|") ); $(".item").each(function() { var $this = $(this); $this[re.source!="" && re.test($this.attr("class")) ? "show" : "hide"](); }); });
you don't need use regular expression this. instead can join()
array create map()
.
build class selector can use directly show required elements. try this:
<ul id="filters"> <li> <input type="checkbox" value="categorya" id="filter-categorya" /> <label for="filter-categorya">category a</label> </li> <li> <input type="checkbox" value="categoryb" id="filter-categoryb" /> <label for="filter-categoryb">category b</label> </li> </ul> <div class="category-container"> <div class="categorya categoryb">a, b</div> <div class="categorya">a</div> <div class="categorya">a</div> <div class="categorya">a</div> <div class="categoryb">b</div> <div class="categoryb">b</div> <div class="categoryb">b</div> </div>
$("#filters :checkbox").click(function() { var filter = '.' + $("#filters :checkbox:checked").map(function() { return this.value; }).get().join("."); $('.category-container div').hide(); $(filter).show(); });
how modify show default until options checked?
to check if selected , show options if not. firstly remove display: none
.categorya, .categoryb
, amend js this:
$("#filters :checkbox").click(function() { var filter = $("#filters :checkbox:checked").map(function() { return this.value; }).get().join("."); if (filter) { $('.category-container div').hide(); $('.' + filter).show(); } else { $('.category-container div').show(); } });
Comments
Post a Comment