简体   繁体   English

如何从HTML下拉菜单中选择值?

[英]How do I pull the value from a selection of a HTML drop down menu?

How do I display the selected option name in the div above it? 如何在其上方的div中显示所选的选项名称? If user has blue selected I want blue to show above. 如果用户选择了蓝色,我希望蓝色显示在上方。

<div id='text"> selection goes here</div>
<select id="dropdownselect">
<option> Red </option>
<option> White </option>
<option> Blue </option>
</select>

Use the following to get the text of the selected option: 使用以下命令获取所选选项的文本:

var select = document.getElementById("dropdownselect");
var selectedText = select.options[select.selectedIndex].text;

Then, to add the value to the div with id text , use: 然后,要将值添加到具有id textdiv ,请使用:

document.getElementById("text").innerHTML = selectedText;

If you want to reflect the selected value every time the option has changed, you need to attach the onchange event to the select , which, combined with the above code results in the following: 如果您想在每次更改选项时都反映所选的值,则需要将onchange事件附加到select ,将其与上面的代码结合使用会导致以下结果:

var select = document.getElementById("dropdownselect");
select.onchange = function () {
  var selectedText = this.options[this.selectedIndex].text;
  document.getElementById("text").innerHTML = selectedText;
};​

Here's a working DEMO . 这是一个正常工作的DEMO

Just add onchange javascript event: 只需添加onchange javascript事件:

<div id="text"> selection goes here</div>
<select id="dropdownselect" onchange="document.getElementById('text').innerHTML = this.options[this.selectedIndex].text;">
    <option> Red </option>
    <option> White </option>
    <option> Blue </option>
</select>​​​​​​​​​​​​​​

You should use a javascript framework to make it much easier. 您应该使用JavaScript框架使其变得更容易。 I personally use jQuery, in which case the javascript to get the value is: 我个人使用jQuery,在这种情况下,要获取值的javascript是:

$("#dropdownselect").val()

And you can change it automatically with: 您可以使用以下方法自动更改它:

<select id="dropdownselect" onChange="$('#text').text($(this).val());">

Similar functions are available with MooTools, or other frameworks I haven't used before. MooTools或我以前未使用过的其他框架也提供了类似的功能。

jQuery can be made available with: jQuery可以通过以下方式使用:

<script src="jquery.js"><!-- assuming you have a jquery file at this location -->
var selectBox = document.getElementById("dropdownselect"),
    textDiv = document.getElementById("text");
textDiv.innerText = selectBox.options[selectBox.selectedIndex].text;

But i'd recommend using jQuery too. 但我建议也使用jQuery。

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

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