I have the following HTML:
<select id="dropdown">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
I have the string "B" so I want to set the selected
attribute on it so it will be:
<select id="dropdown">
<option>A</option>
<option selected="selected">B</option>
<option>C</option>
</select>
How would I do this in jQuery?
This question is related to
jquery
html
html-select
<select id="cars">
<option value='volvo'>volvo</option>
<option value='bmw'>bmw</option>
<option value='fiat'>fiat</option>
</select>
var make = "fiat";
$("#cars option[value='" + make + "']").attr("selected","selected");
You can follow the .selectedIndex strategy of danielrmt, but determine the index based on the text within the option tags like this:
$('#dropdown')[0].selectedIndex = $('#dropdown option').toArray().map(jQuery.text).indexOf('B');
This works on the original HTML without using value attributes.
I'd iterate through the options, comparing the text to what I want to be selected, then set the selected attribute on that option. Once you find the correct one, terminate the iteration (unless you have a multiselect).
$('#dropdown').find('option').each( function() {
var $this = $(this);
if ($this.text() == 'B') {
$this.attr('selected','selected');
return false;
}
});
You can use pure DOM. See http://www.w3schools.com/htmldom/prop_select_selectedindex.asp
document.getElementById('dropdown').selectedIndex = 1;
but jQuery can help:
$('#dropdown').selectedIndex = 1;
$('#select_id option:eq(0)').prop('selected', 'selected');
its good
If you are using JQuery, since the 1.6 you have to use the .prop() method :
$('select option:nth(1)').prop("selected","selected");
Something along the lines of...
$('select option:nth(1)').attr("selected","selected");
Code:
var select = function(dropdown, selectedValue) {
var options = $(dropdown).find("option");
var matches = $.grep(options,
function(n) { return $(n).text() == selectedValue; });
$(matches).attr("selected", "selected");
};
Example:
select("#dropdown", "B");
$(document).on('change', 'select', function () {
var value = $(this).val();
$(this).find('option[value="' + value + '"]').attr("selected", "selected");
})
Source: Stackoverflow.com