How do you select a particular option in a SELECT element in jQuery?

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>

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"})

上述方法都没有提供我需要的解决方案,所以我想我会提供对我有用的东西。

$('#element option[value="no"]').attr("selected", "selected");

你可以使用val()方法:

$('select').val('the_value');
链接地址: http://www.djcxy.com/p/83064.html

上一篇: Jquery从下拉列表中获取SelectedText

下一篇: 你如何在jQuery的SELECT元素中选择一个特定的选项?