I use this code to search about 500 li tags.
$(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 > 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(); } }); });
And here is the HTML:
<input type="text" id="query" value=""/> <ul id="abbreviations"> <li>ABC<span>description</span></li> <li>BCA<span>description</span></li> <li>ADC<span>description</span></li> </ul>
This script is very slow with these many li tags.
How can I do this faster and how can I only search for ABC text in li and not span tags (without changing html)?
I know about existing plugins, but I need a small implementation like this.
Here is a ready-made code for anyone interested
var abbrs = {}; $('ul#abbreviations li').each(function(i){ abbrs[this.firstChild.nodeValue] = i; }); $('#query').focus().keyup(function(e){ if(this.value.length >= 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(); } });
source share