How to find an option tag with a specific value using jQuery

esviko picture esviko · Feb 26, 2011 · Viewed 27.4k times · Source

I'm trying to set an option with a specific value as selected (using jQuery). I've got a string:

var data = '<select><option value="1">A</option><option value="2">B</option><option value="3">C</option></select>';

Now I'm trying to find the option tag with value=2 and set it as selected

$(data).find('option[value=2]').attr('selected','selected');

It's not working. I also tried:

$(data).find('option').each(function(){
if($(this).val()==2){
    $(this).attr('selected','selected');
}
});

which did not work either. How can I make this work?

Answer

user113716 picture user113716 · Feb 26, 2011

Your code works fine, but of course you need to append it to the DOM to see the result. Here I used the appendTo()[docs] method.

Example: http://jsfiddle.net/cqhGH/

 // --v---------------make sure the DOM is loaded
$(function() {
    var data = '<select><option value="1">A</option><option value="2">B</option><option value="3">C</option></select>';

    $(data).appendTo('body').find('option[value=2]').attr('selected','selected');
});

Though an easier way is to use the val()[docs] method.

Example: http://jsfiddle.net/cqhGH/1/

$(function() {
    var data = '<select><option value="1">A</option><option value="2">B</option><option value="3">C</option></select>';

    $(data).appendTo('body').val(2);
});