Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a search filter text box in Jquery?

Assuming I have a div structure with a textbox:

<input id="filter" type="text" name="fname" /><br />
<input type="text">
<div id="listofstuff">
    <div class="anitem">
        <span class="item name">Dog</span>
        <span class="itemdescruption">AboutItem1</span>
    </div>
    <div class="anitem">
        <span class="item name">Doodle Bird</span>
        <span class="itemdescruption">AboutItem2</span>
    </div>
    <div class="anitem">
       <span class="item name">Cat</span>
       <span class="itemdescruption">AboutItem3</span>
    </div>
</div>

I want to make it so that initially.. say it shows 3 anitems, I want to make it so that if the user has any character typed into the search box, it would only show the divs that match with the entry the user is typing.

Ex. So if the user types "D", it would hide all other divs without "D" in the "item name". If the user types another letter "og", then the only div that would be shown is the div with" item name" of "Dog" If the user hits the delete key to remove the "g", then the two divs "Dog" and "Doodle Bird" would be show. If the user deletes everything they typed in the text box, then all the anitems would show up.

How do I accomplish this if possible? I think I may have to use .live() but I'm really not sure.

like image 892
Rolando Avatar asked Jan 08 '12 13:01

Rolando


1 Answers

You will have to handle the keyup event (which is clicked after key is released) then use .filter() to find matching items, showing their parents.

$("#filter").bind("keyup", function() {
    var text = $(this).val().toLowerCase();
    var items = $(".item_name");

    //first, hide all:
    items.parent().hide();

    //show only those matching user input:
    items.filter(function () {
        return $(this).text().toLowerCase().indexOf(text) == 0;
    }).parent().show();
});

Live test case.

like image 165
Shadow Wizard Hates Omicron Avatar answered Nov 01 '22 18:11

Shadow Wizard Hates Omicron