How to create a search filter text box in jQuery?

Assuming I have a div structure with a text box:

 <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 initially .. to say that it shows 3 anitems , I want to make it so that if the user has a character entered in the search field, he will only show divs that correspond to the record that the user enters.

Ex. Therefore, if the user types β€œD”, he will hide all other divs without β€œD” in the β€œelement name”. If the user types another letter β€œog”, then the only div to be displayed is the div with the β€œelement name” β€œDog”. If the user deletes the delete key to delete β€œg”, then two divs β€œDog” and β€œ Doodle Bird. " If the user deletes everything that they typed in the text box, then all the elements will appear.

How to do it, if possible? I think I may have to use .live (), but I'm really not sure.

+6
source share
3 answers

You will have to handle the keyup event (which is keyup after the key is released), then use .filter() to find the matching elements, 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 .

+9
source

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); }); 
0
source

If you want to filter as custom types, you must attach an event handler to the keypress text field [API Ref] . Each time a user presses a key, you can filter [API Ref] the contents of #listofstuff and either show [API Ref] or hide [API Ref] .

0
source

Source: https://habr.com/ru/post/905449/


All Articles