繁体   English   中英

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

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

我有一个标准的下拉列表,我希望它在关闭时显示VALUE ,但在展开以供选择时显示文本。 例如,根据下面的代码,如果用户从列表中选择'Item 3' ,则在关闭列表时应显示3。 我已经可以选择值了,但是我不知道如何重写下拉列表中显示的内容。

感谢任何帮助!

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

声明包含<select> DOM的mySelect变量。 然后,通过使用mySelect ,您可以获取<select>标记的属性。

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

然后,您可以访问作为数组的mySelect选项。

mySelect.options[]

mySelect.selectedIndex将为您提供标签的当前选定索引。

最后,通过附加.text属性,可以设置当前选择的新值。

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

像这样:

 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