Get selected value of a dropdown's item using jQuery

后端 未结 30 1568
广开言路
广开言路 2020-11-22 06:48

How can I get the selected value of a dropdown box using jQuery?
I tried using

var value = $(\'#dropDownId\').val();

and



        
相关标签:
30条回答
  • 2020-11-22 06:59

    For Normal Page loaded dropdowns

      $("#dropDownId").on('change',function(){
         var value=$(this).val();
         alert(value);
      });
    

    for dynamically added options Make sure to keep the id unique

      $(document).on('change','#dropDownId',function(){
        var value=$(this).val();
        alert(value)
      });
    
    0 讨论(0)
  • 2020-11-22 07:00
    $("#selector <b>></b> option:selected").val()
    

    Or

    $("#selector <b>></b> option:selected").text()
    

    Above codes worked well for me

    0 讨论(0)
  • 2020-11-22 07:02
    var value = $('#dropDownId:selected').text()
    

    Should work fine, see this example:

    $(document).ready(function(){ 
      $('#button1').click(function(){ 
        alert($('#combo :selected').text());
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select id="combo">
      <option value="1">Test 1</option>
      <option value="2">Test 2</option>
    </select>
    <input id="button1" type="button" value="Click!" />

    0 讨论(0)
  • 2020-11-22 07:05

    You can do this by using following code.

    $('#dropDownId').val();
    

    If you want to get the selected value from the select list`s options. This will do the trick.

    $('#dropDownId option:selected').text();
    
    0 讨论(0)
  • 2020-11-22 07:05

    If you have more than one dropdown try:

    HTML:

    <select id="dropdown1" onchange="myFunction(this)">
        <option value='...'>Option1
        <option value='...'>Option2
    </select>
    <select id="dropdown2" onchange="myFunction(this)">
        <option value='...'>Option1
        <option value='...'>Option2
    </select>
    

    JavaScript:

        function myFunction(sel) {
            var selected = sel.value;
        }
    
    0 讨论(0)
  • 2020-11-22 07:06

    Yet another tested example:

    <!DOCTYPE html>
    <html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
    </script>
    <script>
    $(document).ready(function(){
        $('#bonus').change(function() {
        alert($("#bonus option:selected").text());
      });  
    });
    </script>
    </head>
    
    <body>
    <select id="bonus">
    <option value="1">-$5000</option>
    <option value="2">-$2500</option>
    <option value="3">$0</option>
    <option value="4">$1</option>
    <option value="5">We really appreciate your work</option>
    </select>
    </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题