How to use jQuery to select a dropdown option?

2020-01-23 10:59发布

I was wondering if it’s possible to get jQuery to select an <option>, say the 4th item, in a dropdown box?

<select>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
</select>

I want the user to click a link, then have the <select> box change its value, as if the user has selected it by clicking on the <option>.

13条回答
甜甜的少女心
2楼-- · 2020-01-23 11:05

Try this:

$('#mySelectElement option')[0].selected = true;

Regards!

查看更多
Summer. ? 凉城
3楼-- · 2020-01-23 11:07

answer with id:

$('#selectBoxId').find('option:eq(0)').attr('selected', true);
查看更多
啃猪蹄的小仙女
4楼-- · 2020-01-23 11:10

I would do it this way

 $("#idElement").val('optionValue').trigger('change');
查看更多
SAY GOODBYE
5楼-- · 2020-01-23 11:13

How about

$('select>option:eq(3)').attr('selected', true);

example at http://www.jsfiddle.net/gaby/CWvwn/


for modern versions of jquery you should use the .prop() instead of .attr()

$('select>option:eq(3)').prop('selected', true);

example at http://jsfiddle.net/gaby/CWvwn/1763/

查看更多
家丑人穷心不美
6楼-- · 2020-01-23 11:13

HTML select elements have a selectedIndex property that can be written to in order to select a particular option:

$('select').prop('selectedIndex', 3); // select 4th option

Using plain JavaScript this can be achieved by:

// use first select element
var el = document.getElementsByTagName('select')[0]; 
// assuming el is not null, select 4th option
el.selectedIndex = 3;
查看更多
倾城 Initia
7楼-- · 2020-01-23 11:13

Use the following code if you want to select an option with a specific value:

$('select>option[value="' + value + '"]').prop('selected', true);
查看更多
登录 后发表回答