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

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

当前回答

var firstItem = $(“感兴趣类型”)。(“selectedIndex”道具,0)。瓦尔();

控制台日志(firstItem)。

其他回答

以下是我的做法:

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

我发现,如果已经有一个选定的属性,只是设置attr选择不工作。我现在使用的代码将首先取消设置所选属性,然后选择第一个选项。

$('#target').removeAttr('selected').find('option:first').attr('selected', 'selected');

如果您有禁用选项,您可以添加not([disabled])以防止选择它们,结果如下:

$("#target option:not([disabled]):first").attr('selected','selected')

Use:

$("#selectbox option:first").val()

请在这个JSFiddle中找到工作简单。

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

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

});