Implementing Javascript Quick Search?

Basically:

  • I have a page with a text box and below <ul> . <ul> populated with the user's friend list.

  • The user begins to enter a friend’s name in the text field, for example, by pressing 'r'

  • I want to immediately update the <ul> with each keystroke, to show only those friends whose names begin with R, for example, "Richard, Redmond, Raheem", etc.

  • As the user enters more, I want to further restrict the names, for example, if the user type is β€œRi”, then I only need β€œRichard” in the list.

I am looking for ideas on how to implement a search. In particular, if I should use the Array or JSON class to store a list of friends, if there is any regex that I should use, etc.?

Also, which jQuery event should I use to listen for keystroke events?

+2
source share
2 answers

Working example: http://jsfiddle.net/peeter/gAAth/

Here is how I would do it, I would not duplicate the data in the array.

Optimized version provided by Raynos: http://jsfiddle.net/gAAth/12/

+7
source

example

Another option based on @Peeter code.

HTML:

 <input type="text" id="input1"/> <ul id="list"> <li>Rich</li> <li>Rajim</li> <li>Andres</li> <li>Jorge</li> <li>Pedro</li> ... <li>Raul</li> <li>Paula</li> <li>Delfina</li> </ul> 

CSS

 li.h {display:none;} 

JS:

contains selector

 $.extend($.expr[':'], { 'containsi': function(elem, i, match, array) { return (elem.textContent || elem.innerText || '').toLowerCase() .indexOf((match[3] || "").toLowerCase()) >= 0; } }); // first option $("#input1").keyup(function() { var search = $(this).val().toLowerCase(); $._list = ($._list) ? $._list : $("#list li"); //cache $._list .removeClass("h") .filter(":not(:containsi('"+search+"'))").addClass("h"); }); 

EDIT

I think a little in the written code, I like to hide first and then display.

example

JS:

 // second option $("#input1").keyup(function() { var search = $(this).val().toLowerCase(); $._list = ($._list) ? $._list : $("#list li"); $._list .addClass(function(index, currentClass) { var addedClass; if (currentClass !== "h" ) addedClass = "h"; return addedClass; }).filter(":containsi('"+search+"')").removeClass("h"); }); // third opcion $("#input1").keyup(function() { var search = $(this).val().toLowerCase(); $._list = ($._list) ? $._list : $("#list li"); $._list .hide() .filter(":containsi('"+search+"')").show(); }); 
+1
source

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


All Articles