Skip to content Skip to sidebar Skip to footer

JQuery - Filtering Data Attributes With Multiple Filters Of Different Inputs

I am working on a project where by I want to use JQuery in order to filter on data variables embedded onto divs that are on the page, its sort of like a showcase in which the users

Solution 1:

So after half a day of playing with JSFiddle I managed to get it working as I wanted, using RegExp as @David Johnson had menntioned.

https://jsfiddle.net/JokerDan/tqv0ybbz/2/

Working HTML

<div class="status"></div>
<div id="filterDiv">
  <input type="text" class="myInput" id="0"/>

  <select class="mySel" id="1">
    <option value="">All</option>
    <option value="a">A</option>
    <option value="b">B</option>
    <option value="c">C</option>
  </select>

  <select class="mySel" id="2">
    <option value="">All</option>
    <option value="123">123</option>
    <option value="231">231</option>
    <option value="321">321</option>
  </select>

  <input type="checkbox" id="3"> Test Data :: 1 | 0 | NULL
</div>
<p class="p a 123" data-name="apple" data-a="a" data-b="123" data-test="1">Apple A 123 1</p>
<p class="p b 123" data-name="banana" data-a="b" data-b="123" data-test="0">Banana B 123 0</p>
<p class="p c 321" data-name="cherry" data-a="c" data-b="321" data-test="">Cherry C 321 X</p>
<p class="p a 321" data-name="date" data-a="a" data-b="321" data-test=""> Date A 321 X</p>
<p class="p a 123" data-name="elderberry" data-a="a" data-b="123" data-test="1">Elderberry A 123 1</p>
<p class="p c 231" data-name="fig" data-a="c" data-b="231" data-test="1">Fig C 231 1</p>

Working JS

$('#filterDiv').on("change keyup", function() {
  chkBox = { datatest: null };

  if ($('#3').is(':checked')) { chkBox.datatest = "1"; } else { chkBox.datatest = ""; }

  $("p").hide().filter(function() {
    var rtnData = "";

    regExName   = new RegExp($('#0').val().trim(), "ig");
    regExA          = new RegExp($('#1').val().trim(), "ig");
    regExB          = new RegExp($('#2').val().trim(), "ig");
    regExTest       = new RegExp(chkBox.datatest, "ig")

    rtnData = (
      $(this).attr("data-name").match(regExName) && 
      $(this).attr("data-a").match(regExA) && 
      $(this).attr("data-b").match(regExB) &&
      $(this).attr("data-test").match(regExTest)
    );

    //console.log(rtnData);
    return rtnData;
  }).show();
});

Solution 2:

Don't you just need to extend the condition like this:

freq = new RegExp($('#frequency').val().trim(), "ig"); 
dips= new RegExp($('#dispwitch').val().trim(), "ig");
clone= new RegExp($('#cloneable').val().trim(), "ig");

return $(this).data("remote-name").match(regExName) || $(this).data("remote-freq").match(freq) || $(this).data("remote-dips").match(dips) || $(this).data("remote-clone").match(clone) 

Post a Comment for "JQuery - Filtering Data Attributes With Multiple Filters Of Different Inputs"