Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically show/hide div based on the input of textbox

Tags:

html

jquery

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

like image 558
Y2theZ Avatar asked Jun 27 '12 14:06

Y2theZ


2 Answers

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

like image 198
David Hedlund Avatar answered Oct 11 '22 12:10

David Hedlund


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.

like image 38
James Allardice Avatar answered Oct 11 '22 13:10

James Allardice