Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 387
esviko Avatar asked Feb 26 '11 17:02

esviko


People also ask

How do you find the value of an option tag?

To get the value of a select or dropdown in HTML using pure JavaScript, first we get the select tag, in this case by id, and then we get the selected value through the selectedIndex property. The value "en" will be printed on the console (Ctrl + Shift + J to open the console).

How do I get the text value of a selected option jQuery?

We can select text or we can also find the position of a text in a drop down list using option:selected attribute or by using val() method in jQuery. By using val() method : The val() method is an inbuilt method in jQuery which is used to return or set the value of attributes for the selected elements.

How do you select a particular option in a select element in jQuery?

Syntax of jQuery Select Option $("selector option: selected"); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $("selector option: selected").

How do you select a particular option in a select element in JavaScript?

Use the selectedIndex and value to get the index and value of the selected option. The HTMLOptionElement represents the <option> element. If the option is selected, the selected property is true. The selectedText and selectedValue properties return the text and value of the selected option.


1 Answers

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);
});
like image 76
user113716 Avatar answered Sep 28 '22 00:09

user113716