简体   繁体   中英

Set value of a select box

I have the following select-box:

<select name="country">
    <option value="us">America</option>
    <option value="jp">Japan</option>
    <option value="cn">China</option>
    <option value="vi">Vietnam</option>
</select>

By default, the value of this select-box is "us" and the displayed text is "America". What I want to do is set the value of this select box to "jp" and set the text displayed on this select-box to "Japan" using javascript.

I can set the value to "jp" easily by setting the "selected" attribute to "true", but I can't change the text display on the select-box (It still display "America" instead of "Japan").

Are there anyone know how to do that?

You need to set the value of the select itself rather than set the options selected to true.

var element = document.getElementsByName('country')[0];
element.value = 'jp';

Can you try this, add selected="selected" based on your preference in HTML, Javascript document.getElementsByName('country')[0].value .

Using HTML:

<select name="country">
    <option value="us">America</option>
    <option value="jp" selected="selected" >Japan</option>
    <option value="cn">China</option>
    <option value="vi">Vietnam</option>
</select>

Using javascript:

  document.getElementsByName('country')[0].value = 'jp';

To use JavaScript, you could use...

selectElement.value = "jp";

jsFiddle .

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