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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6433258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:52:14  来源:igfitidea点击:

Use jQuery to set selected index of a dropdown

jqueryajaxdrop-down-menureset

提问by marky

I have seen other posts here at SOabout this very same subject, but I have not found a solution that is setting the select using jQuery.

我在这里看到过SO关于这个主题的其他帖子,但我还没有找到使用jQuery.

I have a dropdown that looks like this:

我有一个看起来像这样的下拉菜单:

<select type="select" id="docsList" name="docsList"> 
    <option id="defaultListItem" value="0">Select a Document...</option> 
    <option value="38">Document 1</option> 
    <option value="35">Document 2</option> 
    <option value="46">Document 3</option> 
    <option value="45">Document 4</option>          
</select>

I need to reset the dropdown within an $.ajax()successfunction. I've used the following:

我需要在$.ajax()成功函数中重置下拉菜单。我使用了以下内容:

$('select#docsList option:selected').val('0');
$('select#docsList').attr('selectedIndex', 0);

... and some others.

……还有其他一些。

I'm beginning to think this code is fine and I've got something else going on preventing resetting the dropdown.

我开始认为这段代码很好,而且我还有其他事情要阻止重置下拉列表。

回答by Matt Ball

You're overcomplicating things. You don't need jQuery to get/set a <select>'s selectedIndex.

你把事情复杂化了。您不需要 jQuery 来获取/设置 a <select>'s selectedIndex

$('#docsList').get(0).selectedIndex = 0;

When setting the value of a <select>, call .val()on the <select>, not on one of its <option>s.

当设置的值<select>,调用.val()<select>,而不是它的一个<option>秒。

$('#docsList').val('0');

回答by Justin Schwartzenberger

$('#docsList option[value=0]').attr('selected', 'selected');
This will set the <option>with the value attribute set to 0 as the selected option.

$('#docsList option[value=0]').attr('selected', 'selected');
这会将<option>value 属性设置为 0 作为选定选项。

回答by Kate at LittleCollie

Matt's answer has a small flaw:

马特的回答有一个小缺陷:

$('#docsList').val('0');

The code above will not work in IE 9 when not in Compatibility Mode. The following worked cross browsers for me:

当不在兼容模式下时,上面的代码将无法在 IE 9 中工作。以下为我工作的跨浏览器:

document.getElementById('docsList').selectedIndex = 0;

Thanks for the pointer in the right direction, though.

不过,感谢您指向正确方向的指针。

回答by tvanfosson

You want $('select#docsList').val('0');See example at: http://jsfiddle.net/uE2YN/

你想看$('select#docsList').val('0');例子:http: //jsfiddle.net/uE2YN/

回答by Yangon Tharr

$(".btn-reset").click(function () {
    $('#docsList').val('123er43f-12fr-7hgy-ju78-kju345uy65r3');
    $('#docsList').trigger('chosen:updated');
});