使用 jQuery 设置下拉菜单的选定索引

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

$("*[id$='" + originalId + "']")

我这样做是因为我要动态地创建控件,而且因为在使用 Web 窗体时 id 会发生变化,所以我发现这是一种为我找到一些控件的工作。但是一旦我有了 jQuery 对象,我就不知道如何将选中的索引设置为0(零)。

535350 次浏览
$("[id$='" + originalId + "']").val("0 index value");

将其设置为0

首先,那个选择器非常慢。它将扫描每个 DOM 元素寻找 ID。如果可以为元素分配一个类,那么性能损失就会小一些。

$(".myselect")

不过,为了回答您的问题,有几种方法可以更改 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);

您希望获取 select 元素中第一个选项的值。

$("*[id$='" + originalId + "']").val($("*[id$='" + originalId + "'] option:first").attr('value'));

刚找到这个,它对我有用,我个人觉得它更容易阅读。

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

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

这以前不起作用,但现在起作用了: Http://dev.jquery.com/ticket/1474

附录

根据评论中的建议,使用:

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

我在吸毒

$('#elem').val('xyz');

选择具有 value = ‘ xyz’的选项元素

选择第四个选项

$('#select').val($('#select option').eq(3).val());

Jsfiddle 上的例子

JQuery 代码:

$("#sel_status").prop('selectedIndex',1);

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>

我在2015年写这个答案,出于某种原因(可能是旧版本的 jQuery) ,其他的答案都不适合我。我的意思是,他们改变了选择的索引,但它实际上并没有反映在实际的下拉列表中。

下面是另一种改变索引的方法,并且实际上让它反映在下拉列表中:

$('#mydropdown').val('first').change();

选择第二个选项

$('#your-select-box-id :nth-child(2)').prop('selected', true);

在这里,我们添加“触发器(‘ change’)使事件触发。

$('#your-select-box-id :nth-child(2)').prop('selected', true).trigger('change');

这也适用于铬和 Internet Explorer

$("#MainContent_cmbEvalStatus").prop("selectedIndex", 1).change();

根据您的选择放置下拉选项值0,1,2,3,4... ..。

这将奏效:

<head>
<script type="text/javascript">
function Init () {
var counter = document.getElementById ("counter");
for (var i = 1; i < 1000; i++) {
var option = new Option (i, i);
counter.options.add (option);
}
counter.focus ();
}
        

function OnKeyPressCounter (event, counter) {
var chCode = ('charCode' in event) ? event.charCode : event.keyCode;
        

if (chCode == 68 /* + */) {
if (counter.selectedIndex < counter.options.length - 1) {
counter.selectedIndex++;
}
}
if (chCode == 45 /* - */) {
if (counter.selectedIndex > 0) {
counter.selectedIndex--;
}
}
}
</script>
</head>
<body onload="Init ()">
Use the + and - keys to increase/decrease the counter.
<select id="counter" onkeypress="OnKeyPressCounter(event, this)" style="width:80px"></select>
</body>