JQuery matches partial text of a JSON object

I use the real-time search function for my site. I have a JSON object containing key terms that I would like to map to an input value.

The best solution I could think of was to iterate over each term in a loop and look for partial matches with the jQuery selector. How can I make an if statement as follows? For instance:

$.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: I apologize for what you did not understand. I use: contains a selector for partial matches by the value of a single input.

+4
source share
2 answers

One thing you could if you have very small items (say, a few dozen) creates a regular expression matching any of them:

 var match = keys.join("|") var regexp = RegExp.new(match, 'i') // Case insensitive if($(input).val().match(regexp)) { // do stuff } 

Yes, I know that this is not a search for any input matching the conditions, you will need to know the input element in front, but from your question, I assume that you want to check one input element.

I don’t know if it works faster than a cycle in all terms and checks one by one, but I think it is, and it is definitely more readable.

This can be used in conjunction with jQuery grep or each methods:

 var match = keys.join("|") var regexp = RegExp.new(match, 'i') // With grep var matches = $('input').grep(function(elem, idx) { return $(input).val().match(regexp) != null; }) // Or with each $('input')..each(function(idx, elem) { if ($(input).val().match(regexp) != null) { // Do stuff } }); 

grep selects all input fields that match any of the search conditions for later use, and each iterates over all elements to work with them immediately.

+2
source

You need to build the :contains selector as a string:

 if($('input[value]:contains("' + key[i].term + '")').length) { //do something } 

The selector will return all elements where the input contains this term; adding .length provides a simple "true" value for the if-statement to evaluate (0 returned elements == "false" and> 0 returned elements == "true").

EDIT: I'm not sure if input[value]:contains() is a valid jQuery selector, because I don't know what text :contains() looks at the input element. You may need to help a little by checking the value of each input yourself. You can filter the entries found to those where the value contains the term you are looking for:

 if ($('input[value]').filter(function() { return $(this).val().indexOf(key[i].term) != -1; }).length) { //do something } 
+3
source

Source: https://habr.com/ru/post/1434414/


All Articles