在文本字段中显示下拉列表的选定值 (javascript)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10520328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:40:56  来源:igfitidea点击:

Display the selected value of a Drop down list in a text field (javascript)

javascriptformsdrop-down-menu

提问by NLimbu

For Example: These are the items in a drop down list.

例如:这些是下拉列表中的项目。

<select name="cmbitems" id="cmbitems">
    <option value="price1">blue</option>
    <option value="price2">green</option>
    <option value="price3">red</option>
</select>

When the user selects blue, i want to display the value of price1 in a text field below:

当用户选择蓝色时,我想在下面的文本字段中显示 price1 的值:

<input type="text" name="txtprice" id="txtprice" onClick="checkPrice()">

Thank you for answering

谢谢你的回答

回答by jumpnett

All you need to do is set the value of the input to the value of the select, in a select.onchange event handler.

您需要做的就是在 select.onchange 事件处理程序中将输入的值设置为选择的值。

var select = document.getElementById('cmbitems');
var input = document.getElementById('txtprice');
select.onchange = function() {
    input.value = select.value;
}

Hereis a link to a jsFiddle demo

是 jsFiddle 演示的链接

回答by Daniele B

If you are using jqueryjust go with

如果您使用的是jquery,请使用

$('select.foo option:selected').val();    // get the value from a dropdown select

UPDATE ( I forgot to inlcude the <input>population)

更新(我忘了包括<input>人口)

First, inlcude jquery in your html file.

首先,在您的 html 文件中包含 jquery。

In the <header>you include it:

<header>你包括它:

<header>
<script type="text/javascript" src="YOUR_PATH_TO_LIBRARY/jquery-1.7.1-min.js"></script>
</header>

Then

然后

<input type="text" name="txtprice" id="txtprice" onClick="javascript:$('select.foo option:selected').val();">

回答by Rob S

This is the brute force way to look up the currently selected option, check its value and use its display text to update your input. Like Daniele suggested, if you have jquery at your disposal, this gets much, much easier. But if you can't use a JS framework for any reason, this should get you what you need.

这是查找当前选定选项、检查其值并使用其显示文本更新输入的蛮力方法。就像 Daniele 建议的那样,如果您可以使用 jquery,这将变得容易得多。但是,如果您出于任何原因不能使用 JS 框架,这应该可以满足您的需求。

<select name="cmbitems" id="cmbitems" onchange="updateTextField()">
 ...
</select>
<input type="text" ..... />

<script type="text/javascript">
function updateTextField()
{
    var select = document.getElementById("cmbitems");
    var option = select.options[select.selectedIndex];
    if (option.id == "price1")
    {
        document.getElementById("txtprice").value = option.text;
    }
}
</script>

回答by Nick George

$.on('change', '#cmbitems', function() {
    $('#txtprice').val($('#cmbitems option:selected').val());
});