Setting the selected attribute on a select list us

2019-01-08 11:08发布

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?

10条回答
对你真心纯属浪费
2楼-- · 2019-01-08 11:46

This can be a solution

$(document).on('change', 'select', function () {
            var value = $(this).val();
            $(this).find('option[value="' + value + '"]').attr("selected", "selected");
        })
查看更多
放我归山
3楼-- · 2019-01-08 11:48

Something along the lines of...

$('select option:nth(1)').attr("selected","selected"); 
查看更多
姐就是有狂的资本
4楼-- · 2019-01-08 11:50

If you are using JQuery, since the 1.6 you have to use the .prop() method :

$('select option:nth(1)').prop("selected","selected");
查看更多
叼着烟拽天下
5楼-- · 2019-01-08 11:51

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.

查看更多
看我几分像从前
6楼-- · 2019-01-08 12:03
<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");
查看更多
放荡不羁爱自由
7楼-- · 2019-01-08 12:03

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");
查看更多
登录 后发表回答