我如何使第一个选项的选择与jQuery?
<select id="target">
<option value="1">...</option>
<option value="2">...</option>
</select>
我如何使第一个选项的选择与jQuery?
<select id="target">
<option value="1">...</option>
<option value="2">...</option>
</select>
当前回答
$("#target").val($("#target option:first").val());
其他回答
// 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');
Use:
alert($( "#target option:first" ).text());
它只适用于我在最后使用触发器('change'),就像这样:
$("#target option:first").attr('selected','selected').trigger('change');
更改选择输入的值或调整所选属性会覆盖DOM元素的默认selectedOptions属性,导致元素在调用了重置事件的表单中可能无法正确重置。
使用jQuery的prop方法清除和设置所需的选项:
$("#target option:selected").prop("selected", false);
$("#target option:first").prop("selected", "selected");
$("#target").val($("#target option:first").val());