首页 > 解决方案 > 如何使用 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>

我该如何解决这个问题。?

标签: javascripthtmlcssarrayshtml5-canvas

解决方案


您通过 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


推荐阅读