I’m doing a live search results feature for my website. I have a JSON object containing key terms that I’d like to match the value of an input to.
The best solution I could think of for this was to iterate through each term in a loop and look for a partial matches with a jQuery selector. How can I make an if statement like this? For example:
$.getJSON('jsonfile.json', function(data) {
key = Object.keys(data);
for(i=0;i<key.length;i++)
{
if($(input[value]:contains == key[i].term)
{
//do something
}
}
}
EDIT: My apologies for being unclear. I’m using the :contains selector for partial matches on the value of one input.
One thing you could to if you have very little items (say, a few dozen) is create a regular expression matching any of them:
Yes, I know this does not search for any input matching the terms, you’d have to know the input element up front, but from your question I assume you want to check a single input element.
Don’t know if its faster than looping over all terms and checking one by one, but I think it is and it’s definitely more readable.
This can be used in conjunction with jQuery’s
greporeachmethods:The
grepselects all input fields that match any of the search terms for later use, and theeachiterates over all elements to operate on them immediately.