简体   繁体   中英

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. 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. 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. Then by using mySelect , you can get the attributes of the <select> tag.

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

Then, you can access to the mySelect options which is an array.

mySelect.options[]

mySelect.selectedIndex will give you the current selected index of the tag.

Finally, by appending the .text attribute, you can set the new value of the current selection.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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