[英]How to select an <option> within a dropdown by value and assign the “selected” attribute to it?
For a dropdown list ( <select>
), at some point I need to find the option with a given value and assign the selected
attribute to it. 对于下拉列表( <select>
),有时需要找到具有给定值的选项,并将selected
属性分配给它。
eg: 例如:
<select id="font-size">
<option value="12">12px</option>
<option value="13">13px</option>
<option value="14">14px</option>
</select>
In the example above, how would I add the "selected='selected'" attribute to the option
with the value 14? 在上面的示例中,如何将“ selected ='selected'”属性添加到值为14的option
?
This would do it: 这样做:
$('#font-size').val(14);
NB: this sets the selected
property on the required <option>
element - the attribute represents the initital value of the dropdown when the page is first loaded. 注意:这会在必需的<option>
元素上设置selected
属性 -该属性表示首次加载页面时下拉菜单的初始值。
If you need this to set the initial value when the page is loaded then use, 如果在加载页面时需要此设置初始值,请使用,
$(document).ready(function() {
$('#font-size').val(14);
});
or else if you want it the value of which user has selected after the loading use this, 否则,如果您希望使用加载后选择了哪个用户的值,
$(document).ready(function() {
$('#font-size').change(function() {
alert($(this).val());
});
});
document.getElementById("font-size").value = "14";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.