Here is my search filter script on a website; it is simple and works fine.
But if I would like to index specific elements only, what is the right way to do so?
Just for example, only id="type"
and id="taste"
, but not include id="note"
.
$(document).ready(function () {
$("#filter").on("keyup", function () {
var value = $(this).val().toLowerCase();
$("div.item-row").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
});
});
});
.item-row {
margin: 10px 0;
}
p {
line-height: 1.25em;
margin: 0px;
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<input type="text" id="filter"></input>
<div class="list-wrap">
<div class="item-row">
<p id="type">apple</p>
<p id="taste">sweet</p>
<p id="note">note: dummy text</p>
</div>
<div class="item-row">
<p id="type">orange</p>
<p id="taste">sour</p>
<p id="note">note: dummy text</p>
</div>
<div class="item-row">
<p id="type">pineapple</p>
<p id="taste">sour</p>
<p id="note">note: dummy text</p>
</div>
</div>
Edit: When displaying the "filtered results", showing the complete <div class="item-row">
is needed, like this:
input
[ apple ]
___
| apple
| sweet
| note: dummy text
–––
| pineapple
| sour
| note: dummy text
–––
2
Answers
You should use classes instead, as the
id
should beunique
, then instead youfilter
the wholeitem-row
group, you canfilter
ontype
andteste
group, And hidenote
if there is avalue
in theinput
.UPDATE
After OP edited their question I adjusted my script to fully address it:
The
$("div.item-row").filter(function () {...})
will go through all the.item-row
divs and will either show or hide them depending on:$("p:not(.note)",this).text().toLowerCase().indexOf(value) > -1
. This expression collects the lowercase.text()
s from all (but the.note
)<p>
elements in the current div (this
) and looks for an occurence of the lowercase input string in it.