17523

Implementing a Fast Javascript Search?

Question:

Basically:

<ol><li>

I have a page with a textbox, and a <ul> list below it. The <ul> is populated by a list of the user's friends.

</li> <li>

The user begins typing in the name of a friend in the textbox, e.g pressing 'r'

</li> <li>

I want to immediately update the <ul> with each keypress to show only those friends whose names begin with R, e.g 'Richard, Redmond, Raheem', etc.

</li> <li>

As the user types more, I want to further restrict the names, e.g if user types 'Ri' then I only want 'Richard' in the list.

</li> </ol>

I'm looking for ideas on how to implement the searching. Specifically, if I should use an Array or JSON class for storing the list of friends, if there's any regular expression I should use, etc?

Also which jQuery event should I use for listening to the keypress events?

Answer1:

<h2>Working example: <a href="http://jsfiddle.net/peeter/gAAth/" rel="nofollow">http://jsfiddle.net/peeter/gAAth/</a></h2>

This is how I'd do it, I wouldn't duplicate data in an array.

An optimized version provide by Raynos: <a href="http://jsfiddle.net/gAAth/12/" rel="nofollow">http://jsfiddle.net/gAAth/12/</a>

Answer2:

<a href="http://jsfiddle.net/adescalzo/CEP5M/" rel="nofollow">example</a>

Another option based on the @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:

<a href="https://stackoverflow.com/questions/187537/is-there-a-case-insensitive-jquery-contains-selector" rel="nofollow">containsi selector</a>

$.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"); });

<strong>EDIT</strong>

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

<a href="http://jsfiddle.net/adescalzo/CEP5M/1/" rel="nofollow">example</a>

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(); });

Recommend

  • Write JSON data from front-end to back-end in nodejs
  • Why don't we register broadcast receiver for BOOT_COMPLETED events
  • Excel not inserting leading zero
  • Is it possible to disable esc/F11 key during full screen mode of webpage, programmatically?
  • How to set infinite shared access signature policy in azure?
  • How to make a user wait with Laravel
  • How do `pass` and `listen` work in WriterT?
  • Where in the relevant specification is it documented that some comments in a SQL script are, in fact
  • How to get the sql state from libpq?
  • Bash extract user for a particular host from ssh config file
  • Get UILabel out of UIButton
  • Generating anchors with PyYAML.dump()?
  • Raphael.js function getBBox give back NAN/NAN/NAN in IE8
  • matching similar elements in between two lists
  • MVC - @Html.CheckBoxFor
  • Get Currently Active User in Android
  • IE10 strips out hashtag from the URL
  • Create a link to a web page that runs a Javascript function on the page
  • git add error : “fatal : malloc, out of memory”
  • NUnit 3.0 TestCase const custom object arguments
  • Plotting line graph with factors in R
  • How to make JSON.NET deserialize to Microsoft Date Time?
  • Can someone please explain to me in the most layman terms how to use EventArgs?
  • how to display data from 1st point on words on y axis for line chart in d3.js
  • d3 v4 drag and drop with TypeScript
  • Ionic 2 storage is not cleaning up on uninstall - Only for signed APK
  • JQuery Internet Explorer and ajaxstop
  • Can you perform a UNION without a subquery in SQLAlchemy?
  • Row Count Is Returning the incorrect number using RaptureXML
  • Extracting HTML between tags
  • FFmpeg Conversion Error
  • Is there any way to access browser form field suggestions from JavaScript?
  • javaw.exe and eclipse startup problems
  • Opengl-es onTouchEvents problem or a draw problem? [closed]
  • WinForms: two way TextBox problem
  • jQuery tmpl and DataLink beta
  • How to disable jQuery.jplayer autoplay?
  • CSS Applying specific rule for a specific monitor resolution with only CSS is posible?
  • Setting background image for body element in xhtml (for different monitors and resolutions)
  • Linking SubReports Without LinkChild/LinkMaster