基于选择在下拉列表中设置显示值
问题描述:
我有一个标准的下拉列表,我希望它在关闭时显示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>
答
声明mySelect
变量含有<select>
DOM。然后通过使用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>
你想打印在span标记的选定值和所选项目的文本? –
感谢您的回复!不,我的首选项是将其折叠到所选项目的值时更改下拉菜单中显示的文本。 – Jason
你能查看我的答案吗?请让我知道这是否适合你。 –