jQuery select2 get value of select tag?

前端 未结 11 1552
粉色の甜心
粉色の甜心 2020-12-07 15:39

Hello friends this is my code:


                        
    
提交评论

  • 2020-12-07 16:05

    To get Select element you can use $('#first').val();

    To get the text of selected value - $('#first :selected').text();

    Can you please post your select2() function code

    0 讨论(0)
  • 2020-12-07 16:05

    Solution :

    var my_veriable = $('#your_select2_id').select2().val();
    var my_last_veriable = my_veriable.toString();
    
    0 讨论(0)
  • 2020-12-07 16:08

    See this fiddle.
    Basically, you want to get the values of your option-tags, but you always try to get the value of your select-node with $("#first").val().

    So we have to select the option-tags and we will utilize jQuerys selectors:

    $("#first option").each(function() {
        console.log($(this).val());
    });
    

    $("#first option") selects every option which is a child of the element with the id first.

    0 讨论(0)
  • 2020-12-07 16:09

    Above solutions did not work for me with latest select2 (4.0.13)

    With jQuery you can use this solution to retrieve value according to documentation: https://select2.org/programmatic-control/retrieving-selections

    $('#first').find(':selected').val();
    
    0 讨论(0)
  • 提交回复
    热议问题