jQuery Get Selected Option From Dropdown

前端 未结 30 3376
梦如初夏
梦如初夏 2020-11-22 02:56

Usually I use $(\"#id\").val() to return the value of the selected option, but this time it doesn\'t work. The selected tag has the id aioConceptName

相关标签:
30条回答
  • 2020-11-22 03:34

    Usually you'd need to not only get the selected value, but also run some action. So why not avoid all the jQuery magic and just pass the selected value as an argument to the action call?

    <select onchange="your_action(this.value)">
       <option value='*'>All</option>
       <option ... />
    </select>
    
    0 讨论(0)
  • 2020-11-22 03:35

    For dropdown options you probably want something like this:

    var conceptName = $('#aioConceptName').find(":selected").text();
    

    The reason val() doesn't do the trick is because clicking an option doesn't change the value of the dropdown--it just adds the :selected property to the selected option which is a child of the dropdown.

    0 讨论(0)
  • 2020-11-22 03:35

    Have you considered using plain old javascript?

    var box = document.getElementById('aioConceptName');
    
    conceptName = box.options[box.selectedIndex].text;
    

    See also Getting an option text/value with JavaScript

    0 讨论(0)
  • 2020-11-22 03:35

    Use the jQuery.val() function for select elements, too:

    The .val() method is primarily used to get the values of form elements such as input, select and textarea. In the case of select elements, it returns null when no option is selected and an array containing the value of each selected option when there is at least one and it is possible to select more because the multiple attribute is present.

    $(function() {
      $("#aioConceptName").on("change", function() {
        $("#debug").text($("#aioConceptName").val());
      }).trigger("change");
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    
    <select id="aioConceptName">
      <option>choose io</option>
      <option>roma</option>
      <option>totti</option>
    </select>
    <div id="debug"></div>

    0 讨论(0)
  • 2020-11-22 03:38

    Try this for value...

    $("select#id_of_select_element option").filter(":selected").val();
    

    or this for text...

    $("select#id_of_select_element option").filter(":selected").text();
    
    0 讨论(0)
  • 2020-11-22 03:38

    Straight forward and pretty easy:

    Your dropdown

    <select id="aioConceptName">
        <option>choose io</option>
        <option>roma</option>
        <option>totti</option>
    </select>
    

    Jquery code to get the selected value

    $('#aioConceptName').change(function() {
        var $option = $(this).find('option:selected');
    
        //Added with the EDIT
        var value = $option.val(); //returns the value of the selected option.
        var text = $option.text(); //returns the text of the selected option.
    });
    
    0 讨论(0)
提交回复
热议问题