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

mar*_*rky 4 ajax jquery reset drop-down-menu

我在这里看到了SO关于这个相同主题的其他帖子,但我还没有找到一个设置select使用的解决方案jQuery.

我有一个下拉列表,如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)

我需要在$.ajax() 成功函数中重置下拉列表.我用过以下内容:

$('select#docsList option:selected').val('0');
$('select#docsList').attr('selectedIndex', 0);
Run Code Online (Sandbox Code Playgroud)

......和其他一些人.

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

Mat*_*all 14

你的事情太复杂了.你并不需要jQuery来获取/设置<select>selectedIndex.

$('#docsList').get(0).selectedIndex = 0;
Run Code Online (Sandbox Code Playgroud)

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

$('#docsList').val('0');
Run Code Online (Sandbox Code Playgroud)


Jus*_*ger 7

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