简体   繁体   English

如何选择 <option>在按值下拉列表中,并为其分配“选定”属性?

[英]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.

相关问题 如何从下拉列表中分配选项值以选择另一个下拉列表的ID? - How to assign the option value from a dropdown to select id of another dropdown? 如何从DropDown中的选定选项获取title属性的值 - How to get value of title attribute from a selected option in DropDown Select 选项按值和更改所选选项的属性 - Select option by value and change attribute of a selected option 如何将“ selected =&#39;selected&#39;”属性分配给特定 <option>在一个<select>清单。请只使用VanillaJS - How do I assign a “ selected='selected' ” attribute to a specific <option> in a <select> list. VanillaJS only please 在下拉选择菜单中获取所选选项的值 - Get the value of a selected option in a dropdown select menu 如何基于选择的选择选项动态更改输入值属性? - How to change dynamically input value attribute based on select option selected? 在选择选项中选择给出错误的属性值 - selected in select option give wrong attribute value 在“选择”控件中更改所选选项的“值”属性 - Change the “value” attribute of the selected option in “Select” control 使用Dalekjs测试工具,当Option标记中没有“值”属性时,如何在Dropdown(选择元素)中选择Option? - Using Dalekjs test tool, how to select Option in Dropdown(Select element) when there is no “value” attribute in Option tag? Vue.js 选择下拉选项选择属性问题 - Vue.js select dropdown option selected attribute problem
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM