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

时间:2011-06-21 23:38:21

标签: jquery ajax drop-down-menu reset

我在SO处看到了关于同一主题的其他帖子,但我找不到使用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>

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

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

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

我开始认为这段代码很好,我还有其他事情可以防止重置下拉列表。

5 个答案:

答案 0 :(得分:14)

你的事情太复杂了。您不需要jQuery来获取/设置<select>的{​​{1}}。

selectedIndex

设置$('#docsList').get(0).selectedIndex = 0; 的值时,请在<select>上呼叫.val(),而不是<select>之一。

<option>

答案 1 :(得分:7)

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

答案 2 :(得分:4)

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

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

当不在兼容模式下时,上面的代码在IE 9中不起作用。以下为我提供了跨浏览器:

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

感谢指针指向正确的方向。

答案 3 :(得分:3)

您想要$('select#docsList').val('0');请参阅示例:http://jsfiddle.net/uE2YN/

答案 4 :(得分:-1)

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