我如何使第一个选项的选择与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>
当前回答
我发现,如果已经有一个选定的属性,只是设置attr选择不工作。我现在使用的代码将首先取消设置所选属性,然后选择第一个选项。
$('#target').removeAttr('selected').find('option:first').attr('selected', 'selected');
其他回答
$("#target")[0].selectedIndex = 0;
当你使用
$("#target").val($("#target option:first").val());
如果第一个选项值为空,这将在Chrome和Safari中不起作用。
我更喜欢
$("#target option:first").attr('selected','selected');
因为它可以在所有浏览器中工作。
如果你打算使用第一个选项作为默认的
<select>
<option value="">Please select an option below</option>
...
然后你可以使用:
$('select').val('');
它很漂亮,也很简单。
如果您有禁用选项,您可以添加not([disabled])以防止选择它们,结果如下:
$("#target option:not([disabled]):first").attr('selected','selected')
另一种重置值(对于多个选定元素)的方法是:
$("selector").each(function(){
/*Perform any check and validation if needed for each item */
/*Use "this" to handle the element in javascript or "$(this)" to handle the element with jquery */
this.selectedIndex=0;
});