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

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

当前回答

$('选择# 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)

其他回答

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

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

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

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

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

对我有用。

Use:

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

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

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

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

在James Lee Baker的回复后面,我更喜欢这个解决方案,因为它消除了对浏览器支持的依赖:first:selected…

$('#target').children().prop('selected', false);
$($('#target').children()[0]).prop('selected', 'selected');