使用jquery选择下拉选项

dot*_*tty 147 html javascript jquery html-select drop-down-menu

我想知道是否有可能让jQuery在下拉框中选择一个选项,比如说第4项?

<select>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
</select>
Run Code Online (Sandbox Code Playgroud)

我希望用户单击一个链接,然后让选择框更​​改其值,就像用户通过单击选项选择它一样.

Gab*_*oli 179

怎么样

$('select>option:eq(3)').attr('selected', true);
Run Code Online (Sandbox Code Playgroud)

http://www.jsfiddle.net/gaby/CWvwn/上的示例


对于现代版本的jquery,你应该使用.prop()而不是.attr()

$('select>option:eq(3)').prop('selected', true);
Run Code Online (Sandbox Code Playgroud)

例子在http://jsfiddle.net/gaby/CWvwn/1763/

  • @sunnyiitkgp当以编程方式更改值时,永远不会触发`onchange`事件.您可以在末尾添加一个`.trigger('change')`来触发事件(*虽然无论实际更改的值是什么都会触发*) (6认同)
  • 这甚至不应该工作; 选择状态的选项应该通过改变选择本身的状态来触发:) (3认同)

Har*_*OTA 143

解决方案:

$("#element-id").val('the value of the option');
Run Code Online (Sandbox Code Playgroud)

  • 它没有在HTML中设置“ selected”选项。 (2认同)

Ja͢*_*͢ck 53

HTML select元素具有selectedIndex可以写入的属性,以便选择特定选项:

$('select').prop('selectedIndex', 3); // select 4th option
Run Code Online (Sandbox Code Playgroud)

使用纯JavaScript可以通过以下方式实现:

// use first select element
var el = document.getElementsByTagName('select')[0]; 
// assuming el is not null, select 4th option
el.selectedIndex = 3;
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案......看起来是最安全,最干净的解决方案...... (7认同)
  • @GuyKorland jQuery的公开`.trigger()'了,只因为你已经有代码这样做会很容易也自己称呼的改变处理. (4认同)
  • 问题是它不会触发“onchange”事件。 (3认同)
  • @GuyKorland 这种情况与其他任何答案都没有发生,演示 [here](http://jsbin.com/ehahug/1/); 如果要触发事件,则必须手动执行。 (2认同)

小智 25

我会这样做的

 $("#idElement").val('optionValue').trigger('change');
Run Code Online (Sandbox Code Playgroud)

  • 这应该是选择的答案 (3认同)
  • $(“#idElement”)。val('optionValue')。change()也可以工作 (2认同)

Ion*_*zău 22

最简单的方法是val(value)功能:

$('select').val(2);
Run Code Online (Sandbox Code Playgroud)

要获得所选值,您不需要参数:

$('select').val();
Run Code Online (Sandbox Code Playgroud)

另外,如果你有<option value="valueToSelect">...</option>,你可以这样做:

$('select').val("valueToSelect");
Run Code Online (Sandbox Code Playgroud)

DEMO


Vic*_*tor 20

如果您的选项有值,您可以这样做:

$('select').val("the-value-of-the-option-you-want-to-select");
Run Code Online (Sandbox Code Playgroud)

'select'将是您的select或类选择器的id.或者如果只有一个选择,您可以使用示例中的标记.

  • 这正是我所需要的.谢谢. (2认同)

小智 8

如果要选择具有特定值的选项,请使用以下代码:

$('select>option[value="' + value + '"]').prop('selected', true);
Run Code Online (Sandbox Code Playgroud)


小智 5

 Try with the below codes. All should work. 
    $('select').val(2);
    $('select').prop('selectedIndex', 1);
    $('select>option[value="5"]').prop('selected', true);
    $('select>option:eq(3)').attr('selected', 'selected');
    $("select option:contains(COMMERCIAL)").attr('selected', true);
Run Code Online (Sandbox Code Playgroud)