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

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

当前回答

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

控制台日志(firstItem)。

其他回答

当你使用

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

如果第一个选项值为空,这将在Chrome和Safari中不起作用。

我更喜欢

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

因为它可以在所有浏览器中工作。

// 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');

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

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

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

它只适用于我在最后使用触发器('change'),就像这样:

$("#target option:first").attr('selected','selected').trigger('change');

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