我如何使第一个选项的选择与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>
当前回答
另一种重置值(对于多个选定元素)的方法是:
$("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;
});
其他回答
当你使用
$("#target").val($("#target option:first").val());
如果第一个选项值为空,这将在Chrome和Safari中不起作用。
我更喜欢
$("#target option:first").attr('selected','selected');
因为它可以在所有浏览器中工作。
Use:
$("#selectbox option:first").val()
请在这个JSFiddle中找到工作简单。
var firstItem = $(“感兴趣类型”)。(“selectedIndex”道具,0)。瓦尔();
控制台日志(firstItem)。
这对我很管用!
$("#target").prop("selectedIndex", 0);
// 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');