Reputation: 1873
I want to select an option in a string, where the string will be the contents of a dropdown, but I dont know how to loop through the string as an object please. In the example I would like "Saab" to be selected and the string alerted.
var x = '<select><option>Volvo</option> <option>Saab</option> <option>Mercedes</option> <option>Audi</option> </select>';
$.each($(x), function(index, value) {
if ($(this).val() == "Saab"){
$(this).attr("selected","selected")
}
});
alert(x);
Upvotes: 0
Views: 3924
Reputation: 318212
Start by turning the string into a jQuery object:
var x = $(x);
Then just select the correct option and set it as selected:
$('option:contains("Saab")', x).prop('selected', true);
Upvotes: 3
Reputation: 13956
Don't need to loop, jquery can do that for ya
$(x).children('option:contains("Saab")').attr('selected','selected');
ref: http://api.jquery.com/category/selectors/
Upvotes: 0
Reputation: 5761
Is this in an HTML page? If yes, why not just use something like $("option").each()?
Upvotes: 0
Reputation: 5817
$.each($('option', x), function(index, value) {
if ($(this).text() == "Saab"){
$(this).attr("selected","selected")
}
});
Upvotes: 0