简体   繁体   English

设置选择框的值

[英]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". 默认情况下,此选择框的值为“ us”,显示的文本为“ 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. 我想做的就是将此选择框的值设置为“ jp”,并使用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"). 我可以通过将“ selected”属性设置为“ true”来轻松地将值设置为“ jp”,但是我无法更改选择框上的文本显示(它仍然显示“ America”而不是“ 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. 您需要设置选择本身的值,而不是将选择的选项设置为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 . 您能尝试一下吗,根据您在HTML,Javascript document.getElementsByName('country')[0].value首选项添加selected="selected"

Using HTML: 使用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: 使用javascript:

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

To use JavaScript, you could use... 要使用JavaScript,您可以使用...

selectElement.value = "jp";

jsFiddle . jsFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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