Note that there are some explanatory texts on larger screens.

plurals
  1. POSearch through a big list fast with jQuery
    text
    copied!<p>I'm using this code to search trough about 500 li tags.</p> <pre><code>$(function() { $.expr[":"].containsInCaseSensitive = function(el, i, m){ var search = m[3]; if (!search) return false; return eval("/" + search + "/i").test($(el).text()); }; $('#query').focus().keyup(function(e){ if(this.value.length &gt; 0){ $('ul#abbreviations li').hide(); $('ul#abbreviations li:containsInCaseSensitive(' + this.value + ')').show(); } else { $('ul#abbreviations li').show(); } if(e.keyCode == 13) { $(this).val(''); $('ul#abbreviations li').show(); } }); }); </code></pre> <p>And here is the HTML:</p> <pre><code>&lt;input type="text" id="query" value=""/&gt; &lt;ul id="abbreviations"&gt; &lt;li&gt;ABC&lt;span&gt;description&lt;/span&gt;&lt;/li&gt; &lt;li&gt;BCA&lt;span&gt;description&lt;/span&gt;&lt;/li&gt; &lt;li&gt;ADC&lt;span&gt;description&lt;/span&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>This script is very slow with this many li tags.</p> <p>How can I make it faster, and how can I search trough only the ABC text in the li, and not the span tags (without changing the html) ?</p> <p>I know about the existing plugins, but I need a small implementation like this. <br /><br /></p> <p><b>Here's the finished code for anyone interested</b></p> <pre><code>var abbrs = {}; $('ul#abbreviations li').each(function(i){ abbrs[this.firstChild.nodeValue] = i; }); $('#query').focus().keyup(function(e){ if(this.value.length &gt;= 2){ $('ul#abbreviations li').hide(); var filterBy = this.value.toUpperCase(); for (var abbr in abbrs) { if (abbr.indexOf(filterBy) !== -1) { var li = abbrs[abbr]; $('ul#abbreviations li:eq('+li+')').show(); } } } else { $('ul#abbreviations li').show(); } if(e.keyCode == 13) { $(this).val(''); $('ul#abbreviations li').show(); } }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload