I have the below HTML code, also I will have a textbox for entering the keyword, What I want is while the user writing in this textbox the javascript search in this HTML code using the FirstName and LastName, and while comparing items, if an item didn’t match I want to display: none its container div. How can I do that using JS and work on firefox and IE
<div id='contact_4'> <input class='contactChk' id='chk_4' type='checkbox' /> <img alt='' src='img/4.jpg' width='25px' height='25px' /> <span id='contactName_4' class='contactItem'> FirstName LastName </span> <br /> </div> <div id='contact_5'> <input class='contactChk' id='chk_5' type='checkbox' /> <img alt='' src='img/5.jpg' width='25px' height='25px' /> <span id='contactName_5' class='contactItem'> ACharName AnyLast </span> <br /> </div> <div id='contact_6'> <input class='contactChk' id='chk_6' type='checkbox' /> <img alt='' src='img/6.jpg' width='25px' height='25px' /> <span id='contactName_6' class='contactItem'> BCharName AnyLast </span> <br /> </div> <div id='contact_7'> <input class='contactChk' id='chk_7' type='checkbox' /> <img alt='' src='img/7.jpg' width='25px' height='25px' /> <span id='contactName_7' class='contactItem'> CCharName AnyLast </span> <br /> </div>
This looks very inefficient if you have a larger set of contacts to be displayed. The easiest way would be to use jQuery and bind a function to keyup event of your text field: (assuming the above code is contained inside something like
<div id='contactlist'>)Also add
.matchingand.nonmatchingclasses to your CSS. (display: blockandnone)As said, this is quite inefficient, not only by memory (and bandwidth) needed but also by CPU time on filtering (plus rendering time). It could be faster if you process that data inside some array or if you have very large datasets you should fetch the filtered data paginated from server on demand (can also be done by jQuery’s AJAX functions). You could also filter delayed in case the user is still typing (filter only if he stopped typing for ~500ms).
toLowerCase()could have some difficulties with non-ASCII input; so if you need it you should test it on your target languages.