Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  118] [ 4]  / answers: 1 / hits: 16006  / 13 Years ago, sun, january 8, 2012, 12:00:00

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.


More From » jquery

 Answers
52

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.


[#88158] Friday, January 6, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
megb

Total Points: 230
Total Questions: 113
Total Answers: 100

Location: Tokelau
Member since Sun, May 7, 2023
1 Year ago
;