Peter PitLock
Peter PitLock

Reputation: 1873

Loop through string of dropdown options and select

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

Answers (4)

adeneo
adeneo

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);

FIDDLE

Upvotes: 3

Nhu Trinh
Nhu Trinh

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

Roy Tang
Roy Tang

Reputation: 5761

Is this in an HTML page? If yes, why not just use something like $("option").each()?

Upvotes: 0

$.each($('option', x), function(index, value) { 
    if ($(this).text() == "Saab"){
        $(this).attr("selected","selected")
    }
});

Upvotes: 0

Related Questions