简体   繁体   中英

Select2 reinitialize not working

I have a selectbox, which is dependent on another selectbox. I'm using AJAX to change options on the second (dependent) selectbox. Also, I'm using select2 plugin on both of the selectboxes, something like:

$(document).ready(function() {
    $('#mySelect2').select2({
        // options
        }
    });
});

My problem is that after refreshing the second selectbox, select2 just disappears from this selectbox and shows to me just like a normal selectbox. Somewhere here, I have seen that I can use destroy and "reinit" the select. But in mySelect1.onChange event when I use:

$('#mySelect2').select2("destroy");
$('#mySelect2').select2({
        // same options
});

it looks like that selectbox is destroyed but not initialized again. Because after another refresh, my console says:

The select2('destroy') method was called on an element that is not using Select2.

Thanks for any answer, I'm new to this.

Try not destroying the select2 element, loading new data link and then .trigger('change') link . For example:

// new data arrived...
var new_data = [...]

$('#mySelect2').select2({
    // update data
    data: new_data
});
$('#mySelect2').trigger("change");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM