I’m trying to initiate a search (or rather filter) on keypress for an image library. The user starts typing in the name of an image, and any image name that doesn’t match the search term gets hidden:
<div id="abc" data-imgName="abc"></div>
<div id="abc2" data-imgName="abc2"></div>
<div id="xyz" data-imgName="xyz"></div>
So if a user starts typing in “ab”, then: $('#xyz').hide();
How can I do this? Can I use regex on an attribute?
There is probably a way to do this that performs better but this takes the value of the text input and finds all the elements with the
data-imgNameattribute that contains the value of the text input. It then finds all the elements with thedata-imgNameattribute and hides all of the elements that have not been found already.If you have a parent element to all of the searched elements, you should start all the selectors with it to avoid searching the entire DOM:
Notice that this example also checks if the value of the text box is nothing, if so then it shows all of the searched elements.
Here are docs for the
*=(contains) selector: http://api.jquery.com/attribute-contains-selector/Here are docs for the
.not()function: http://api.jquery.com/notHere is a working demo: http://jsfiddle.net/HRjHV/3/