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

时间:2015-10-15 00:28:18

标签: javascript drop-down-menu

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

1 个答案:

答案 0 :(得分:1)

声明包含mySelect DOM的<select>变量。然后,使用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>