如何使用jQuery选择第一个选项?
<select id="target">
<option value="1">...</option>
<option value="2">...</option>
</select>
Run Code Online (Sandbox Code Playgroud)
Dav*_*res 911
$("#target").val($("#target option:first").val());
Run Code Online (Sandbox Code Playgroud)
小智 163
你可以试试这个
$("#target").prop("selectedIndex", 0);
Run Code Online (Sandbox Code Playgroud)
use*_*513 108
// remove "selected" from any options that might already be selected
$('#target option[selected="selected"]').each(
function() {
$(this).removeAttr('selected');
}
);
// mark the first option as selected
$("#target option:first").attr('selected','selected');
Run Code Online (Sandbox Code Playgroud)
Jim*_*ang 65
当你使用
$("#target").val($("#target option:first").val());
Run Code Online (Sandbox Code Playgroud)
如果第一个选项值为null,则无法在Chrome和Safari中使用.
我更喜欢
$("#target option:first").attr('selected','selected');
Run Code Online (Sandbox Code Playgroud)
因为它可以在所有浏览器中使用.
Jam*_*ker 43
更改选择输入的值或调整所选属性可能会覆盖DOM元素的默认selectedOptions属性,从而导致元素在调用了重置事件的表单中无法正确重置.
使用jQuery的prop方法清除并设置所需的选项:
$("#target option:selected").prop("selected", false);
$("#target option:first").prop("selected", "selected");
Run Code Online (Sandbox Code Playgroud)
Bra*_*ard 19
我认为我发现最高投票答案的一个微妙之处在于即使他们正确地更改了所选值,他们也不会更新用户看到的元素(只有当他们点击小工具时他们才会看到旁边的支票.更新的元素).
将.change()调用链接到最后也将更新UI小部件.
$("#target").val($("#target option:first").val()).change();
Run Code Online (Sandbox Code Playgroud)
(请注意,我在使用jQuery Mobile和Chrome桌面上的一个框时注意到了这一点,所以在任何地方都可能不是这样).
Mel*_*nie 15
如果您已禁用选项,则可以不添加([禁用])以防止选择它们,结果如下:
$("#target option:not([disabled]):first").attr('selected','selected')
Run Code Online (Sandbox Code Playgroud)
小智 15
重置值(对于多个选定元素)的另一种方法可能是:
$("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;
});
Run Code Online (Sandbox Code Playgroud)
小智 7
很简单:
$('#target option:first').prop('selected', true);
Run Code Online (Sandbox Code Playgroud)
我发现如果已经选择了属性,那么只设置选中的attr不起作用.我现在使用的代码将首先取消设置所选属性,然后选择第一个选项.
$('#target').removeAttr('selected').find('option:first').attr('selected', 'selected');
Run Code Online (Sandbox Code Playgroud)
我将如何做到这一点:
$("#target option")
.removeAttr('selected')
.find(':first') // You can also use .find('[value=MyVal]')
.attr('selected','selected');
Run Code Online (Sandbox Code Playgroud)
虽然每个功能可能不是必需的......
$('select').each(function(){
$(this).find('option:first').prop('selected', 'selected');
});
Run Code Online (Sandbox Code Playgroud)
为我工作。