javascript - 如何使用 JavaScript 函数从 Select Option 标记中获取值
问题描述
我有一个这样的下拉列表:
<select id="itemsList" onchange="gettingList()">
<option>Please select the option</option>
<option value="50">Soap</option>
<option value="100">Sugar</option>
<option value="290">Oil</option>
</select>
<br><br>
我必须在下面的输入标签中获取上面列表的值。
<input type="text" id="price">
为此,我正在使用这个脚本。
<script>
function gettingList() {
var selectItem = document.getElementById('itemsList').value;
var displayPrice = selectItem.options[selectItem.selectedIndex].text;
document.getElementById('price').value = displayPrice;
}
</script>
我该如何解决这个问题。?
解决方案
您通过 selectvalue
属性获得选定的价格。现在,您可以使用它更新输入。
function gettingList() {
var selectItemPrice = document.getElementById('itemsList').value;
document.getElementById('price').value = selectItemPrice;
}
<select id="itemsList" onchange="gettingList()">
<option>Please select the option</option>
<option value="50">Soap</option>
<option value="100">Sugar</option>
<option value="290">Oil</option>
</select>
<br><br>
<input type="text" id="price">
有关选择元素的更多信息- https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select
推荐阅读
- c++ - 动态分配对象中的字段 - 更好的动态或静态分配?C++
- git - 如何为每个项目设置 yarn version-tag-prefix 和 version-git-message?
- docker - 让 docker build --memory-swap=20g 使用可用的交换空间?
- r - 使用 scatter3D() (package plot3D) 在 R 中绘制多元线性回归
- javascript - 行为不同的外部 JS 文件
- c# - C# SaveFileDialog 使用从 API 中提取的 JSON 数据
- reactjs - SpringBoot with React - Rest API 在刷新时与 React Routes 发生冲突
- regex - 正则表达式:用 SublimeText 3 中的文件完整路径的一部分替换文本
- typescript - TS 如何解释具有相同命名函数属性但不同签名的类型的交集(与接口相同生成错误)?
- java - Java - 将实例变量传递给 this() 方法