Reputation: 2790
Given some simple JSON:
["62689", "62690", "62697"]
I need to select the three elements in the DOM that correspond to these values (based on value
attribute). They could be a <select>
, <input>
, <option>
or anything really.
What selector should I be using for this?
Upvotes: 2
Views: 5580
Reputation: 22663
You need a forEach loop and a Attribute selectors - CSS declare your array like this
markup
<input type=text value=62689 />
<input type=text value=62690 />
<input type=text value=62697 />
script
var selectedArray = ["62689", "62690", "62697"];
selectedArray.forEach(function(e){
$('[value='+e+']').hide();
});
Or if you need more that one just conbine them like this $('input[value='+e+'],select#hider option[value='+e+']').attr('selected', 'selected');
<input type=text value=62689 />
<input type=text value=62690 />
<input type=text value=62697 />
<select id="hider" value=626973>
<option value=62689>Show</option>
<option>Hide</option>
</select>
script
var selectedArray = ["62689", "62690", "62697"];
selectedArray.forEach(function(e){
$('input[value='+e+'],select#hider option[value='+e+']').attr('selected', 'selected');
});
Upvotes: 2
Reputation: 2606
You can try something like this. :
var array = ["62689", "62690", "62697"];
$("SelectControl").filter(function() {
return jquery.inArray($(this).val(), array) > -1;
})
Upvotes: 2
Reputation: 128816
You can use jQuery's Attribute Equals Selector.
Selects elements that have the specified attribute with a value exactly equal to a certain value.
For example to select the element whose value
is 62689
, you'd use:
$('[value="62689"]')
To select all three, you'd use:
$('[value="62689"], [value="62690"], [value="62697"]')
If you want to apply some method to these elements and you have more or less than those exact three values, you can just loop through your JSON response and apply accordingly:
var data = ["62689", "62690", "62697"];
for (var i = 0; i < data.length; i++)
$('[value="' + data[i] + '"]');
Or you can just pull them all into an array using jQuery's map()
method:
var elements = $('input, select').map(function() {
if ($.inArray(this.value, data) != -1)
return this;
return false;
}).get();
Upvotes: 3
Reputation: 13347
Look into jQuery selectors.
For this case I would use something like
$('[value="' + items[0] + '"]')
Where items
is the array result from your JSON.
Upvotes: 0