Reputation: 69
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
Upvotes: 4
Views: 8343
Reputation: 313
Excellent answer by @omarjebari, but for programmers who want to return multiple elements with different data attribute and different data attribute value were both ARE NOT always present
<p class='my-class' data-attribute1='1'></p>
<p class='my-class' data-attribute2='2'></p>
// data-attribute1 OR data-attribute2
$(".my-class").filter(`[data-attribute1="${firstID}"],[data-attribute2="${secondID}"]`);
When looking to return multiple elements with different data attribute and different data attribute value were both ARE always present
<p class='my-class' data-attribute1='1' data-attribute2='1'></p>
<p class='my-class' data-attribute1='1' data-attribute2='2'></p>
// data-attribute1 AND data-attribute2
$(".my-class").filter(`[data-attribute1="${firstID}"][data-attribute2="${secondID}"]`);
The placement of the comma is crucial to differentiate between finding with OR or an AND argument.
It also works for elements who have the same data attribute but with different attribute value
$(".my-class").filter(`[data-attribute1="${firstID}"],[data-attribute1="${secondID}"]`);
Upvotes: 0
Reputation: 5499
Another option is to use multiple selectors then filter on them.
item 1 etc
Then you can filter on:
// data-type1 AND data-type-2
if ($(this).find('[data-type1="Primary"][data-type-2="Academy"]').length) {
//stuff
}
// data-type1 OR data-type-2
if ($(this).find('[data-type1="Primary"],[data-type-2="Academy"]').length) {
//stuff
}
Upvotes: 7
Reputation: 25352
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"));
}
})
Upvotes: 2