JavaScript,如何从一个列表中获取选定的值,同时在另一个列表中进行更改

JavaScript, how to grab the selected value from one list and simultaneously change in another list

本文关键字:列表 另一个 获取 JavaScript 一个      更新时间:2023-09-26

我有 2 个选择列表。有一个复选框,单击它时需要将所选值馈送到另一个列表中。

我已经到了设法提醒第一个选择列表中的选定值的阶段,我的问题是如何在单击复选框时获取第二个选择列表中的值:

请检查下面的代码,了解我走了多远:

<!DOCTYPE html>
    <html>
    <head>
    <script type="text/javascript">
    function displayResult() {
      if(document.form1.billingtoo.checked == true) {
        var x = document.getElementById("mySelect").selectedIndex;
        var y = document.getElementById("mySelect").options;
        alert(y[x].text);
      }
    }
    </script>
    </head>
    <body>
    <form name="form1">
    Select your favorite fruit:
        <select id="mySelect">
            <option>Apple</option>
            <option>Orange</option>
            <option>Pineapple</option>
            <option>Banana</option>
        </select>
        <br>
        <input type="checkbox" name="billingtoo" onclick="displayResult()">
        <br>
    Select your favorite fruit 2:
        <select id="mySelect2">
            <option>Apple</option>
            <option>Orange</option>
            <option>Pineapple</option>
            <option>Banana</option>
        </select>
    </form>
    </body>
    </html>

谢谢。

只需设置其他选择元素的选定索引。

js小提琴示例

if(document.form1.billingtoo.checked == true) {
        var x = document.getElementById("mySelect").selectedIndex;
        var y = document.getElementById("mySelect").options;
        // Set selected index for mySelect2
        document.getElementById("mySelect2").selectedIndex = x;
}

您可以getset objectvalue property,如果您担心选项的顺序不同。

js小提琴示例

if(document.form1.billingtoo.checked == true) {
        var x = document.getElementById("mySelect").value;
        var y = document.getElementById("mySelect").options;
        document.getElementById("mySelect2").value = x;       
}
相关文章: