使用jQuery设置下拉列表的选定索引

oz.*_*oz. 161 jquery

如果我找到控件的方式如下,如何设置jQuery中下拉列表的索引:

$("*[id$='" + originalId + "']") 
Run Code Online (Sandbox Code Playgroud)

我是这样做的,因为我正在动态创建控件,并且由于在使用Web窗体时更改了id,我发现这是一个解决方法,可以找到一些控件.但是一旦我有了jQuery对象,我就不知道如何将所选索引设置为0(零).

gna*_*arf 343

首先 - 选择器很慢.它将扫描每个寻找id的DOM元素.如果您可以为元素分配类,那么它将不会受到性能影响.

$(".myselect")
Run Code Online (Sandbox Code Playgroud)

要回答您的问题,有几种方法可以更改jQuery中的select元素值

// sets selected index of a select box to the option with the value "0"
$("select#elem").val('0'); 

// sets selected index of a select box to the option with the value ""
$("select#elem").val(''); 

// sets selected index to first item using the DOM
$("select#elem")[0].selectedIndex = 0;

// sets selected index to first item using jQuery (can work on multiple elements)
$("select#elem").prop('selectedIndex', 0);
Run Code Online (Sandbox Code Playgroud)


4im*_*ble 105

刚发现这个,它对我有用,我个人觉得它更容易阅读.

这将设置实际索引,就像gnarf的答案3号选项一样.

// sets selected index of a select box the actual index of 0 
$("select#elem").attr('selectedIndex', 0);
Run Code Online (Sandbox Code Playgroud)

这本来不起作用,但现在确实...看错误:http: //dev.jquery.com/ticket/1474

附录

根据评论中的建议使用:

$("select#elem").prop('selectedIndex', 0);

  • 从jQuery 1.6开始,你应该使用`.prop('selectedIndex',0);`不管`.attr()`是否有效:) (30认同)

Pau*_*ulG 10

我在2015年写这个答案,由于某些原因(可能是旧版本的jQuery),其他答案都没有对我有用.我的意思是,他们更改了所选的索引,但实际上并没有反映实际的下拉列表.

这是另一种更改索引的方法,实际上它反映在下拉列表中:

$('#mydropdown').val('first').change();
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的回答。只有这个答案对我有用 (2认同)
  • 对于它的价值,应该指出的是,你在这里做的不同就是在下拉列表中触发`change`事件,这对于那些通过调用`prop更改选择的人来说也是一个有用的修复/解决方法('selectedIndex',...)`,而不是`val(...)`.也许问题在于你正在听一个'改变'事件,那是什么不适合你?确实,简单地改变'prop`erty不会触发任何事件...... (2认同)

小智 9

我正在使用

$('#elem').val('xyz');
Run Code Online (Sandbox Code Playgroud)

选择value ='xyz'的选项元素


小智 9

JQuery代码:

$("#sel_status").prop('selectedIndex',1);
Run Code Online (Sandbox Code Playgroud)

Jsp代码:

Status:
<select name="sel_status"
    id="sel_status">
    <option value="1">-Status-</option>
    <option>ALL</option>
    <option>SENT</option>
    <option>RECEIVED</option>
    <option>DEACTIVE</option>
</select>
Run Code Online (Sandbox Code Playgroud)