Reputation: 175
I am trying to create this search function which hides all <li>
where HTML is not equal to <input>
value.
How can I accomplish that with jQuery?
$('input').keypress(function(){
if($('ul li').html != $('input').val()) {
$(this).hide();
}
});
Upvotes: 2
Views: 3035
Reputation: 914
You need something more like this:
$('input').keypress(function() {
var inputValue = $("input").val().toLowerCase();
$("li").each(function() {
if($(this).html().toLowerCase().indexOf(inputValue) == -1)
{
$(this).hide();
}
else
{
$(this).show();
}
});
});
Upvotes: 4
Reputation: 36784
You should listen to the keyup
event so that you can get the value of the <input>
after the keystroke. You could hide all of your list items, .filter()
out the one that matches, and show it. Compare the values both in lower-case to get a case-insensitive comparison.
Also, comparing the values like that wouldn't strictly 'search' for the value entered, it would only show the item if exactly that were to be typed. You could search through the substrings of each of the <li>
s HTML of the same length as the value:
$('input').keyup(function(){
var value = $(this).val().toLowerCase();
$('ul li').hide().filter(function(){
return $(this).html().substring(0, value.length).toLowerCase() == value;
}).show();
});
Remember this won't account for any leading/trailing white-space, but there's $.trim()
for that.
Upvotes: 3