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?
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).
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.
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").
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With