user1512356 user1512356 -4 years ago 84
jQuery Question

Filter by multiple data attribute elements

I've got some list items i want to filter using selects if the data attribute has all of the select option values not just if it has one or another.

<li class="filterme" data-type="Primary Academy Physical KS1">item 1</li>
<li class="filterme" data-type="Secondary Academy Physical KS2">item</li>
<li class="filterme" data-type="Secondary Academy Physical KS1">item 1</li>
<li class="filterme" data-type="Academy Physical KS1">item 1</li>


I have some select boxes firing an onchange event which first hides all items

$('.filterme').hide();


And i then want to show if a data attribute contains all values passed to it. I tried

$(".filterme[data-type*='" + Secondary && Physical && KS1 + "']").show();


Which i want to show this one

<li class="filterme" data-type="Secondary Academy Physical KS1">item 1</li>


But it doesnt show any matches
I can get it to work with just one value, but how do i check if a data attribute contains multiple values, not OR but AND?

thanks

Answer Source

Try like this

$(".filterme").each(function() {
  if ($(this).data("type").indexOf("Secondary") > -1 && $(this).data("type").indexOf("Physical") > -1 && $(this).data("type").indexOf("KS1") > -1) {
    console.log($(this).data("type"));
  }
})

DEMO

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download