简体   繁体   English

使用JavaScript在下拉菜单中显示选项的键和值

[英]Displaying key and values of the options in a dropdown using javascript

 function keyy(id) { var value; var selected; var select = document.getElementById(id); if(value != null) select.options[selected].text = value; selected = select.selectedIndex; var key; key =select.options[selected].value; value= select.options[selected].text; select.options[selected].innerHTML = key; } 
 <select id="Carss" name="Cars" onchange="keyy(this.id)" > <option value="A">Audi</option> <option value="M">Mercedes</option> </select> 

I have n dropdown values. 我有n个下拉列表值。 When I select one value, the corresponding key should be displayed. 当我选择一个值时,应显示相应的键。 The drop down should be the values and the display item shoud be the coresponding key. 下拉列表应为值,显示项目应为核心键。

Have atached the image for the reference. 已将图像作为参考。

My code : 我的代码:

var value;
var selected;
function keyy(id) {
     var select = document.getElementById(id);
     if(value != null)
         select.options[selected].text = value; 
     selected = select.selectedIndex;
     var key;
     key =select.options[selected].value;
     value= select.options[selected].text;
     select.options[selected].text = key; 
}

What you're trying to do is impossible (with a native <select> ). 您要尝试执行的操作是不可能的(使用本机<select> )。 The item you see in the closed <select> is simply the <option> that is currently selected. 您在闭合的<select>看到的项目只是当前选择的<option> When you open the drop-down, you see the same <option> in two places - in the "selection" and in the "list". 当打开下拉列表时,您会在两个位置(“选择”和“列表”中)看到相同的<option> You cannot see a different value in each of the places, when it's the same <option> . 当相同的<option>时,您无法在每个位置看到不同的值。

You could, however, show the selected value somewhere else, eg in a second element next to the <select> . 但是,您可以在其他地方显示所选的 ,例如,在<select>旁边的第二个元素中。

This is not a perfect answer.. But a possible work around.. 这不是一个完美的答案。但是可以解决。

 function key() { document.getElementById("Carss").style.width = "100px" } function key2() { document.getElementById("Carss").style.width = "34px" document.getElementById("Carss").blur(); } 
 <select id="Carss" name="Cars" onfocus="key()" onchange="key2()" style="width:34px"> <option value="A">Audi</option> <option value="M">Mercedes</option> </select> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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