我如何使第一个选项的选择与jQuery?
<select id="target">
<option value="1">...</option>
<option value="2">...</option>
</select>
我如何使第一个选项的选择与jQuery?
<select id="target">
<option value="1">...</option>
<option value="2">...</option>
</select>
当前回答
你可以试试这个
$("#target").prop("selectedIndex", 0);
其他回答
虽然每个函数可能都不是必需的…
$('select').each(function(){
$(this).find('option:first').prop('selected', 'selected');
});
对我有用。
我发现,如果已经有一个选定的属性,只是设置attr选择不工作。我现在使用的代码将首先取消设置所选属性,然后选择第一个选项。
$('#target').removeAttr('selected').find('option:first').attr('selected', 'selected');
$("#target")[0].selectedIndex = 0;
更改选择输入的值或调整所选属性会覆盖DOM元素的默认selectedOptions属性,导致元素在调用了重置事件的表单中可能无法正确重置。
使用jQuery的prop方法清除和设置所需的选项:
$("#target option:selected").prop("selected", false);
$("#target option:first").prop("selected", "selected");
您可以使用它从下拉菜单中选择任何选项。
// 'N' can by any number of option. // e.g., N=1 for first option
$("#DropDownId").val($("#DropDownId option:eq(N-1)").val());