jQuery select2 get value of select tag?

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

Hello friends this is my code:


                        
    
提交评论

  • 2020-12-07 15:47

    Other answers wasn't working for me so i developed solution:

    I created option with class="option-item" for easy targeting

    HTML :

    <select id="select-test">
    <option value="5-val" id="first-id" class="option-item"> First option </option>
    </select>
    

    Then for every selected option i added display none property

    CSS:

    option:checked {
       display: none;
    }
    

    Now we can add change to our SelectBox to find our selected option with display none property by simple :hidden attribute

    JQuery:

    $('#select-test').change(function(){
    //value 
        $('#select-test').find('.option-item:hidden').val();
    //id
        $('#select-test').find('.option-item:hidden').attr('id');
    //text
        $('#select-test').find('.option-item:hidden').text();
    });
    

    Working fiddle: https://jsfiddle.net/Friiz/2dk4003j/10/

    0 讨论(0)
  • 2020-12-07 15:49

    This solution allows you to forget select element. Helpful when you do not have an id on select elements.

    $("#first").select2()
    .on("select2:select", function (e) {
        var selected_element = $(e.currentTarget);
        var select_val = selected_element.val();
    });
    
    0 讨论(0)
  • 2020-12-07 15:52

    $("#first").select2('data') will return all data as map

    0 讨论(0)
  • 2020-12-07 15:54

    If you are using ajax, you may want to get updated value of select right after the selection.

    //Part 1
    
    $(".element").select2(/*Your code*/)    
    
    //Part 2 - continued 
    
    $(".element").on("select2:select", function (e) { 
      var select_val = $(e.currentTarget).val();
      console.log(select_val)
    });
    

    Credits: Steven-Johnston

    0 讨论(0)
  • 2020-12-07 15:58

    Simple answer is :

    $('#first').select2().val()
    

    and you can write by this way also:

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