I want to make a live search with jQuery. Here's my code:
$("#searchInput").on("keyup", function () {
var searchTerm = $("#searchInput").val();
$('li:contains("' + searchTerm + '")').show().siblings(':not(li:contains("' + searchTerm + '"))').hide();
});
Showing <li> which contains "searched text" work properly but the second part (hiding the rest of the items) doesn't work completely.
How can I hide <li>s when I search for unrelated word?
You can use jQuery.not
Solution 1
$("#searchInput").on("keyup", function() {
var searchTerm = $("#searchInput").val();
$("ul li").show().not($('li:contains("' + searchTerm + '")')).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="searchInput" />
<ul>
<li>
Hello
</li>
<li>
World
</li>
<li>
List 1
</li>
<li>
Word
</li>
<li>
Another Li
</li>
</ul>
You can use jQuery filter ( see below snippet)
Solution 2
$("#searchInput").on("keyup", function() {
var searchTerm = $("#searchInput").val();
$("ul li").show().filter(function() {
return $(this).text().indexOf(searchTerm) == -1
}).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="searchInput" />
<ul>
<li>
Hello
</li>
<li>
World
</li>
<li>
List 1
</li>
<li>
Word
</li>
<li>
Another Li
</li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With