Javascript checkbox tag filter: Issue to hide results when unchecked

时间:2019-04-17 00:20:32

标签: javascript jquery checkbox filter

I have this content filter with checkbox that works getting the .text inside the option.

The issue is that It does not reset after uncheck, and show all the content that suppose to be filtered.

$("#filters :checkbox").click(function() {

   var re = new RegExp($("#filters :checkbox:checked").map(function() {
                          return this.value;
                       }).get().join("|") );
   $("div").each(function() {
      var $this = $(this);
      $this[re.source!="" && re.test($this.text().toLowerCase()) ? "show" : "hide"]();
   });
});

It should clean the results.

The whole code is here in JsFiddle https://jsfiddle.net/4fhkzxdp/2/

1 个答案:

答案 0 :(得分:1)

When $("#filters :checkbox:checked") is empty (when all the checkboxes are unchecked), the string used to create new RegExp is empty. If you use that expression, it's going to match all your elements and display them.

var myRegexp = new RegExp('') // /(?:)/

Quick hack would be to store checked boxes in a variable and in the each loop check to see if that array is empty - if it is, none of the elements will be visible. Here's how you could do it: https://jsfiddle.net/3t2hydmn/