简体   繁体   English

根据选择在下拉列表中设置显示值

[英]Set Display Value in Dropdown List Based on Selection

I have a standard drop down list and I would like it to display the VALUE when closed but the text when expanded for selection. 我有一个标准的下拉列表,我希望它在关闭时显示VALUE ,但在展开以供选择时显示文本。 For example, based on my code below, if the user selects 'Item 3' from the list, 3 should be displayed when the list is closed. 例如,根据下面的代码,如果用户从列表中选择'Item 3' ,则在关闭列表时应显示3。 I'm to the point where I can get the value selected but I don't know how to rewrite what is displayed in the drop down list. 我已经可以选择值了,但是我不知道如何重写下拉列表中显示的内容。

Appreciate any help! 感谢任何帮助!

<script type="text/javascript">
function setValue()
{
    var value=document.getElementById("mySelect").value;
    //Don't know what to put here
}
</script>

<select name="mySelect" id="mySelect" onchange="setValue();">
    <option value="1" selected="">Item 1</option>
    <option value="2">Item 2</option>
    <option value="3">Item 3</option>
    <option value="4">Item 4</option>
</select>

Declare the mySelect variable which contains the <select> DOM. 声明包含<select> DOM的mySelect变量。 Then by using mySelect , you can get the attributes of the <select> tag. 然后,通过使用mySelect ,您可以获取<select>标记的属性。

var mySelect = document.getElementById("mySelect");

Then, you can access to the mySelect options which is an array. 然后,您可以访问作为数组的mySelect选项。

mySelect.options[]

mySelect.selectedIndex will give you the current selected index of the tag. mySelect.selectedIndex将为您提供标签的当前选定索引。

Finally, by appending the .text attribute, you can set the new value of the current selection. 最后,通过附加.text属性,可以设置当前选择的新值。

mySelect.options[mySelect.selectedIndex].text = mySelect.value;

Something like this: 像这样:

 function setValue() { var mySelect = document.getElementById("mySelect"); mySelect.options[mySelect.selectedIndex].text = mySelect.value; } 
 <select name="mySelect" id="mySelect" onchange="setValue();"> <option value="1" selected="">Item 1</option> <option value="2">Item 2</option> <option value="3">Item 3</option> <option value="4">Item 4</option> </select> 

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

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