Reputation: 62626
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.
Upvotes: 6
Views: 16913
Reputation: 14411
You want to handle the keyup event and i think you can do this:
$('div').each(function() {
$(this).toggle($(this).children('span.itemname').text() == yourVar);
});
Upvotes: 0
Reputation: 66389
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();
});
Upvotes: 10
Reputation: 23142
If you want to filter as the user types, you should attach an event handler to the textbox's keypress
[API Ref] event. Everytime the user presses a key, you can filter
[API Ref] the contents of #listofstuff
and either show
[API Ref] or hide
[API Ref] it.
Upvotes: 0