我如何使第一个选项的选择与jQuery?

<select id="target">
  <option value="1">...</option>
  <option value="2">...</option>
</select>

当前回答

以下是我的做法:

$("#target option")
    .removeAttr('selected')
    .find(':first')     // You can also use .find('[value=MyVal]')
        .attr('selected','selected');

其他回答

您可以使用它从下拉菜单中选择任何选项。

// 'N' can by any number of option.  // e.g.,  N=1 for first option
$("#DropDownId").val($("#DropDownId option:eq(N-1)").val()); 

另一种重置值(对于多个选定元素)的方法是:

$("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;

});

对我来说,只有当我添加下面这行代码时,它才能工作

$('#target').val($('#target').find("option:first").val());

更改选择输入的值或调整所选属性会覆盖DOM元素的默认selectedOptions属性,导致元素在调用了重置事件的表单中可能无法正确重置。

使用jQuery的prop方法清除和设置所需的选项:

$("#target option:selected").prop("selected", false);
$("#target option:first").prop("selected", "selected");

我认为,关于投票最多的答案,我发现了一个微妙的问题:即使它们正确地更改了所选的值,它们也不会更新用户看到的元素(只有当用户单击小部件时,才会在更新的元素旁边看到一个复选框)。

将.change()调用链接到末尾也会更新UI小部件。

$("#target").val($("#target option:first").val()).change();

(注意,我是在使用jQuery Mobile和Chrome桌面框时注意到这一点的,所以这可能不是到处都是情况)。