简体   繁体   中英

Check for values in multidimensional input array

I store values in a multi-dimensional hidden input array that looks like this:

<input type="hidden" name="tokens[0][Search_Type]" value="a" />
<input type="hidden" name="tokens[0][Search_Term]" value="123" />
<input type="hidden" name="tokens[1][Search_Type]" value="b" />
<input type="hidden" name="tokens[1][Search_Term]" value="456" />

How can I quickly check whether there is a token with Search_Term = X and Search_Type = Y? If there's a way to do it in one jquery line rather than in a loop that'd be awesome.

You could do it with selectors as well:

// found
console.log($('input[name$="[Search_Type]"][value="a"]').next('input[name$="[Search_Term]"][value="123"]').length); 

// not found
console.log($('input[name$="[Search_Type]"][value="b"]').next('input[name$="[Search_Term]"][value="123"]').length); 

// found
console.log($('input[name$="[Search_Type]"][value="b"]').next('input[name$="[Search_Term]"][value="456"]').length); 

Example: http://jsfiddle.net/niklasvh/56jLf/

But whether or not that is more efficient than with looping, I don't know.

Jquery:

token_found = $('input[name$=Search_Type]][value=Y]
                 +
                 input[name$=Search_Term]][value=X]'
               ).length > 0;

If you are checking the submitted array as a javascript object, you can use jsonpath to perform xpath like queries on a dataset.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM