如何将选择框的值添加到文本框? [英] How to add the value of selectbox to a textbox?

查看:94
本文介绍了如何将选择框的值添加到文本框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个选择框,我想根据更改选择框将它们的值添加到选择框.我写了下面的代码.但它只适用于一个. 我怎样才能做到这一点 ? 这是我的代码:

i have 2 select box and i want to add value of them to a selectbox based onchange selectbox. i wrote the below code. but it is working only for one . how can i do this ? here is my code :

var selectBox = document.getElementById('mySelect');
var selectBox2 = document.getElementById('mySelect2');

selectBox.addEventListener('change', handleChange);
selectBox2.addEventListener('change', handleChange);
                           
function handleChange()
{
    var selectedValue = this.options[this.selectedIndex].value;
    document.getElementById('myInput').value = selectedValue;
    document.getElementById('myInput2').value = selectedValue;

}

<select id="mySelect">
    <option value="Option 1">Option 1</option>
    <option value="Option 2">Option 2</option>
    <option value="Option 3">Option 3</option>
</select>
<select id="mySelect2">
    <option value="Option 1">Option 1</option>
    <option value="Option 2">Option 2</option>
    <option value="Option 3">Option 3</option>
</select>


<input type="text" id="myInput" />
<input type="text" id="myInput2" />

推荐答案

var selectBox = document.getElementById('mySelect');
var selectBox2 = document.getElementById('mySelect2');

selectBox.addEventListener('change', handleChange);
selectBox2.addEventListener('change', handleChange);
                           
function handleChange(event)
{
    if (event.target.id == "mySelect") {
      document.getElementById('myInput').value = selectBox.value;
    } else {
      document.getElementById('myInput2').value = selectBox2.value;
    }
}

<select id="mySelect">
    <option value="Option 1">Option 1</option>
    <option value="Option 2">Option 2</option>
    <option value="Option 3">Option 3</option>
</select>
<select id="mySelect2">
    <option value="Option 1">Option 1</option>
    <option value="Option 2">Option 2</option>
    <option value="Option 3">Option 3</option>
</select>


<input type="text" id="myInput" />
<input type="text" id="myInput2" />

这篇关于如何将选择框的值添加到文本框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆