Write jQuery code to filter a list while typing in a search box
Description: When the user types in the search box, show only the list items which contain the text. The search must not depend on upper or lower case.
Hint:
- Use
.toggle(condition)andindexOf()on lowercase text.
HTML of the page
<input type="text" id="search">
<ul id="names">
<li>Anita</li>
<li>Ravi</li>
<li>Maya</li>
<li>Manish</li>
</ul>
Solution
$('#search').on('input', function () {
var term = $(this).val().toLowerCase();
$('#names li').each(function () {
var match = $(this).text().toLowerCase().indexOf(term) !== -1;
$(this).toggle(match);
});
});
$('#search').val('MA').trigger('input');
$('#names li').each(function () {
console.log($(this).text() + ': ' + $(this).css('display'));
});
Console output
Anita: none
Ravi: none
Maya: list-item
Manish: list-item
How it works
- The search text “MA” matches “Maya” and “Manish”.
.toggle(true)shows an element and.toggle(false)hides it.
Read jQuery each() and Effects.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |