简体   繁体   中英

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.

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?

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.

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM