【问题标题】:I want to catch the value of selected item on change of dropdown list我想在下拉列表更改时捕获所选项目的值
【发布时间】:2020-11-01 23:31:46
【问题描述】:

我想在某个变量的下拉列表中获取所选项目的值,并在我的代码中使用它。我想将此数据用于此列表旁边的另一个下拉列表:

    <html>
         <head>
         <title>Home Page</title>
         <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">        
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
   </head>
        <body>
        <button id="mybtn">Emp Name</button>
        <div>
        <select id="output">    
         <script>
                 $('#mybtn').click(function () {
                 $.getJSON('empData', function (data) {
                 $("select#output > option").remove();
                 $.each(data, function (key, value) {
                 $("#output").append('<option>' + value['empId'] + " " + value['empName'] +'</option>');                 
                  });
                  });
                  }); 
            </script>
        </select>
        </div>
        </body>
            </html>

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    如果它的多选下拉菜单,您必须将所选值推送到数组中,并且当取消选择时,您必须从数组中弹出值。然后您可以在另一个下拉菜单中使用该数组。

    使用下面的代码来获取下拉列表中的值:

    var select = document.getElementById('output');
    var value = select.value;
    

    这将为您提供选定的值。

    【讨论】:

    • 能否请您告诉我,如何在网页上显示选定的值。
    • 只需将变量放在您希望显示文本的位置即可。
    • 我无法显示该值。你能帮忙提供完整的代码吗?
    【解决方案2】:

    原版 JavaScript:

    var o = document.getElementById("output");
    var value = o.options[o.selectedIndex].value;
    var text = o.options[o.selectedIndex].text;
    

    jQuery:

    $("#output:selected").text(); // The text content of the selected option
    $("#output:selected").val(); // The value of the selected option
    

    【讨论】:

    猜你喜欢
    • 2018-03-12
    • 2023-03-29
    • 2012-10-14
    • 1970-01-01
    • 2013-02-25
    • 2012-05-23
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    相关资源
    最近更新 更多