javascript - 如何将选择框的文本显示到文本框?

标签 javascript jquery

如何根据所选事件向每个文本框显示选择框的文本? 我的代码仅显示选择框到文本框的值。我想用每个选项的文本替换它。

这是我的代码:

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"> this Text</option>
    <option value="Option 2">this Text 2</option>
</select>
<select id="mySelect2">
    <option value="Option 1">this Text</option>
    <option value="Option 2">this Text 2 </option>
</select>


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

最佳答案

您可以使用选择元素上的 selectedOptions[0].text 访问所选选项的标签。

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.selectedOptions[0].text;
    } else {
      document.getElementById('myInput2').value = selectBox2.selectedOptions[0].text;
    }
}

// Set initial values:
document.getElementById('myInput').value = selectBox.selectedOptions[0].text;
document.getElementById('myInput2').value = selectBox2.selectedOptions[0].text;
<select id="mySelect">
    <option value="Option 1"> this Text</option>
    <option value="Option 2">this Text 2</option>
</select>
<select id="mySelect2">
    <option value="Option 1">this Text</option>
    <option value="Option 2">this Text 2 </option>
</select>


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

关于javascript - 如何将选择框的文本显示到文本框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46137688/

相关文章:

jquery - 如何使可拖动捕捉到可放置并允许交换?

php - 将参数从一个页面上的 JS/Jquery 传递到另一个页面上的 PHP

javascript - chop javascript中的文本,不包括html元素

适合新手的 JavaScript 代码

javascript - 为什么我的数据对象变量在我没有重新分配操纵值时被更改?

javascript - 将 json 响应保存为常量

灰尘模板渲染后的 JavaScript 验证

javascript - 获取全局 JQuery $(document).ajaxSuccess 函数以在所有浏览器中工作

javascript - 在表格中添加 <tr> 元素

javascript - 为什么在尝试控制台 $.each 中的日志值时出现错误?