Get custom data-attribute in select2 with <select>

前端 未结 8 825
我寻月下人不归
我寻月下人不归 2020-12-05 18:38

Let\'s assume you have the following HTML5


                        
    
提交评论

  • 2020-12-05 18:44

    Select2 v4 relies on <select> tags instead of hidden <input> tags so it's now easier to get the selected option or options: you just refer to the original <select>. This may have also been the case with Select2 v3 but I've only used Select2 v4.

    $('#example option:selected').attr('data-id')
    

    jsfiddle demonstration

    See also Get selected value in dropdown list using JavaScript?

    Edit: I like this answer for general purpose data object access:

    var d = $("#dropdown").select2("data");
    

    d will be an array containing the selected item(s) as objects, so to access the id property of the first item:

    var id = d[0].id;
    
    0 讨论(0)
  • 2020-12-05 18:48

    After hours of trying to solve this, I have manage to pull out the attribute. I am using 3.5.4

    $("#select2").select2('data').element[0].attributes[1].nodeValue
    

    HTML

    <select id="select2" name="course" class="form-control">
      <option></option>  
      <optgroup label="Alabama">  
        <option value="City 1" data-url="/alabama/city-1">City 1</option>  
        <option value="City 2" data-url="/alabama/city-2">City 2</option>  
      </optgroup>  
    </select>

    $("#select2").select2('data').element[0].attributes[0].nodeValue --> Value Attribute
    $("#select2").select2('data').element[0].attributes[1].nodeValue --> Data-URl Attribute

    0 讨论(0)
  • 2020-12-05 18:49
    $(document).ready(function() {
        $('select#myselect').select2({
            templateResult: formatOutput
        });
    
    });
    function formatOutput (item) {
        var $state = $(item.element).data('id') + ' ' + item.text;
        return $state;
    };
    
    0 讨论(0)
  • 2020-12-05 18:51

    There is no direct method with select2, you can use a combinaison of select2 data and jQuery :

    $("#example").select2().find(":selected").data("id");
    

    First you get the select2 data then you find your selected option with jQuery and finally the data-attribute.

    0 讨论(0)
  • 2020-12-05 18:54

    so simple, using jquery api [tested against select2 4.x version]

    $('#select').on('select2:select', function (e) {
        let id = $(e.params.data.element).data('id');
    });
    
    0 讨论(0)
  • 提交回复
    热议问题