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?
If you don't mind modifying your HTML a little to include the value
attribute of the options, you can significantly reduce the code necessary to do this:
<option>B</option>
to
<option value="B">B</option>
This will be helpful when you want to do something like:
<option value="IL">Illinois</option>
With that, the follow jQuery will make the change:
$("select option[value='B']").attr("selected","selected");
If you decide not to include the use of the value
attribute, you will be required to cycle through each option, and manually check its value:
$("select option").each(function(){
if ($(this).text() == "B")
$(this).attr("selected","selected");
});
<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");
如果您使用的是JQuery,则从1.6开始,您必须使用.prop()方法:
$('select option:nth(1)').prop("selected","selected");
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 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.
$(document).on('change', 'select', function () {
var value = $(this).val();
$(this).find('option[value="' + value + '"]').attr("selected", "selected");
})
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;
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");
$('#select_id option:eq(0)').prop('selected', 'selected');
很好
类似于...
$('select option:nth(1)').attr("selected","selected");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.