select2 changing items dynamically

前端 未结 6 1824
执笔经年
执笔经年 2020-12-02 09:23

I have two selects that are linked: Each value of the first select determines which items will be displayed in the second select.

The values of the second select are

相关标签:
6条回答
  • 2020-12-02 09:27

    Try using the trigger property for this:

    $('select').select2().trigger('change');
    
    0 讨论(0)
  • 2020-12-02 09:28

    I'm successfully using the following to update options dynamically:

    $control.select2('destroy').empty().select2({data: [{id: 1, text: 'new text'}]});

    0 讨论(0)
  • 2020-12-02 09:28

    I fix the lack of example's library here:

    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" rel="stylesheet"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js">
    

    http://jsfiddle.net/bbAU9/328/

    0 讨论(0)
  • 2020-12-02 09:30

    In my project I use following code:

    $('#attribute').select2();
    $('#attribute').bind('change', function(){
        var $options = $();
        for (var i in data) {
            $options = $options.add(
                $('<option>').attr('value', data[i].id).html(data[i].text)
            );
        }
        $('#value').html($options).trigger('change');
    });
    

    Try to comment out the select2 part. The rest of the code will still work.

    0 讨论(0)
  • 2020-12-02 09:34

    For v4 this is a known issue that won't be addressed in 4.0 but there is a workaround. Check https://github.com/select2/select2/issues/2830

    0 讨论(0)
  • 2020-12-02 09:42

    I've made an example for you showing how this could be done.

    Notice the js but also that I changed #value into an input element

    <input id="value" type="hidden" style="width:300px"/>
    

    and that I am triggering the change event for getting the initial values

    $('#attribute').select2().on('change', function() {
        $('#value').select2({data:data[$(this).val()]});
    }).trigger('change');
    

    Code Example

    Edit:

    In the current version of select2 the class attribute is being transferred from the hidden input into the root element created by select2, even the select2-offscreen class which positions the element way outside the page limits.

    To fix this problem all that's needed is to add removeClass('select2-offscreen') before applying select2 a second time on the same element.

    $('#attribute').select2().on('change', function() {
        $('#value').removeClass('select2-offscreen').select2({data:data[$(this).val()]});
    }).trigger('change');
    

    I've added a new Code Example to address this issue.

    0 讨论(0)
提交回复
热议问题