JQuery - how to select dropdown item based on valu

2019-01-16 17:30发布

I want set a dropdown(select) to be change based on the value of the entries.

I have

<select id="mySelect">
  <option value="ps">Please Select</option>
  <option value="ab">Fred</option>
  <option value="fg">George</option>
  <option value="ac">Dave</option>
</select>

And I know that I want to change the dropdown so that the option with the value of "fg" is selected. How can I do this with JQuery?

10条回答
闹够了就滚
2楼-- · 2019-01-16 18:07
$('#yourdropddownid').val('fg');

Optionally,

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

where 3 is the index of the option you want.

Live Demo

查看更多
Deceive 欺骗
3楼-- · 2019-01-16 18:08

You should use

$('#dropdownid').val('selectedvalue');

Here an example:

$('#dropdownid').val('selectedvalue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='dropdownid'>
    <option value=''>- Please choose -</option>
    <option value='1'>1</option>
    <option value='2'>2</option>
    <option value='selectedvalue'>There we go!</option>
    <option value='3'>3</option>
    <option value='4'>4</option>
    <option value='5'>5</option>
</select>

查看更多
戒情不戒烟
4楼-- · 2019-01-16 18:09
$('#mySelect').val('ab').change();
查看更多
乱世女痞
5楼-- · 2019-01-16 18:15
$('#mySelect').val('fg');...........
查看更多
登录 后发表回答