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

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

当前回答

虽然每个函数可能都不是必需的…

$('select').each(function(){
    $(this).find('option:first').prop('selected', 'selected');
});

对我有用。

其他回答

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

控制台日志(firstItem)。

$('#newType option:first').prop('selected', true);

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

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

以下是我的做法:

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

$('选择# id”)。瓦尔($ (' # id选项”)(指数)value)

将id替换为特定的选择标记id,将索引替换为要选择的特定元素。

即。

<select class="input-field" multiple="multiple" id="ddlState" name="ddlState">
                                        <option value="AB">AB</option>
                                        <option value="AK">AK</option>
                                        <option value="AL">AL</option>
</select>

所以这里的第一个元素选择,我将使用以下代码:

$('select#ddlState').val($('#ddlState option')[0].value)