How do you select a particular option in a SELECT

2018-12-31 15:12发布

If you know the Index, Value or Text. also if you don't have an ID for a direct reference.

This, this and this are all helpful answers.

Example markup

<div class="selDiv">
  <select class="opts">
    <option selected value="DEFAULT">Default</option>
    <option value="SEL1">Selection 1</option>
    <option value="SEL2">Selection 2</option>
  </select>
</div>

标签: jquery
19条回答
不流泪的眼
2楼-- · 2018-12-31 15:45

You could name the select and use this:

$("select[name='theNameYouChose']").find("option[value='theValueYouWantSelected']").attr("selected",true);

It should select the option you want.

查看更多
与风俱净
3楼-- · 2018-12-31 15:45

try this new one

Exactly it will works

<script>    
    $(document).ready(function() {
    $("#id").val('select value here');
       });
        </script>
查看更多
不流泪的眼
4楼-- · 2018-12-31 15:48

I use this, when i know the index of the list.

$("#yourlist :nth(1)").prop("selected","selected").change();

This allows the list to change, and fire the change event. The ":nth(n)" is counting from index 0

查看更多
明月照影归
5楼-- · 2018-12-31 15:50
   $(elem).find('option[value="' + value + '"]').attr("selected", "selected");
查看更多
情到深处是孤独
6楼-- · 2018-12-31 15:52

A selector to get the middle option-element by value is

$('.selDiv option[value="SEL1"]')

For an index:

$('.selDiv option:eq(1)')

For a known text:

$('.selDiv option:contains("Selection 1")')

EDIT: As commented above the OP might have been after changing the selected item of the dropdown. In version 1.6 and higher the prop() method is recommended:

$('.selDiv option:eq(1)').prop('selected', true)

In older versions:

$('.selDiv option:eq(1)').attr('selected', 'selected')

EDIT2: after Ryan's comment. A match on "Selection 10" might be unwanted. I found no selector to match the full text, but a filter works:

 $('.selDiv option')
    .filter(function(i, e) { return $(e).text() == "Selection 1"})

EDIT3: Use caution with $(e).text() as it can contain a newline making the comparison fail. This happens when the options are implicitly closed (no </option> tag):

<select ...>
<option value="1">Selection 1
<option value="2'>Selection 2
   :

If you simply use e.text any extra whitespace like the trailing newline will be removed, making the comparison more robust.

查看更多
回忆,回不去的记忆
7楼-- · 2018-12-31 15:52

None of the methods above provided the solution I needed so I figured I would provide what worked for me.

$('#element option[value="no"]').attr("selected", "selected");
查看更多
登录 后发表回答