I am working on a website, I have a page containing a list of persons built like this:
<div class="personsMenu">
<div class="person">
<div class="name">John</div>
<div class="age">18</div>
</div>
<div class="person">
<div class="name">Kate</div>
<div class="age">24</div>
</div>
<div class="person">
<div class="name">Tom</div>
<div class="age">17</div>
</div>
</div>
I also have a textbox <input type="Text" id="filterTextBox"/>
Using jquery i need to do the following:
When the user start typing in the textbox the divs where the "name" does not contain the characters disappears (some sort of a dynamic filter, you only see the persons who's name contains the written characters)
So the logic should be like this:
When the user type a character in the textbox (or remove one) we loop through all the "person" divs and if the "name" div inside that "person" contains the characters we show it, otherwise we hide it (.show() and .hide() in jquery)
And of course if the textbox is empty we show everything.
Can this be done?
Thanks for any help
At every keystroke, you could .toggle()
each .person
, passing a variable indicating whether or not it matches the current value, and should thus be shown.
$('.my-textbox').keyup(function() {
var value = $(this).val();
var exp = new RegExp('^' + value, 'i');
$('.personsMenu .person').each(function() {
var isMatch = exp.test($('.name', this).text());
$(this).toggle(isMatch);
});
});
Modify the expression as you see fit. In this version, it checks that the name starts with the value entered, and ignores casing.
Demo
Here's something to get you started. I'm sure it's far from perfect, but you haven't shown what you've already tried and what's gone wrong in your question.
$("#filterTextBox").on("keyup", function () {
var search = this.value;
$(".person").show().filter(function () {
return $(".name", this).text().indexOf(search) < 0;
}).hide();
});
Here's a working example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With