2015-10-15 149 views
0

我有一个标准的下拉列表,我希望它在关闭时显示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> 
+0

你想打印在span标记的选定值和所选项目的文本? –

+0

感谢您的回复!不,我的首选项是将其折叠到所选项目的值时更改下拉菜单中显示的文本。 – Jason

+0

你能查看我的答案吗?请让我知道这是否适合你。 –

回答

1

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

+1

这样做 - 谢谢TON! – Jason

+0

@丹尼这取代了下拉文本。问题是如果显示值可以显示为选定的值。不知道为什么这被接受,因为这会改变每个选择的文本 – santon