jquery select2 refresh data

北慕城南 提交于 2021-01-27 04:02:01

问题


I using select2 to select and ajax to load data, how can I replace old data when the state is changed after initial selection.

My loading code:

$('.datetimepicker').on("changeDate", function() {  
        //refresh selectbox ??
        doctor_id = $(".select2-doctors").val();
        clinic_id = $(".select2-clinics").val();
        date = $('.datetimepicker').datepicker('getFormattedDate');
        $.ajax({
            url: '/admin/appointments/time_slots',
            type: 'GET',
            dataType: 'json',
            data: {doctor_id: doctor_id, clinic_id: clinic_id, date: date}
        })
        .done(function(data) {
            console.log("success");
            console.log(data);
            $('.select2-slot').select2({
                data: data.slots
            });
        })
        .always(function() {
            console.log("complete");
        });
    });

回答1:


Try emptying the select2 options before to update data, this because by default it appends data to existing options.

$('.select2-slot').empty();
$('.select2-slot').select2({
    data: data.slots
});



回答2:


instance && $('.select2').empty();
var instance = $('.select2').select2({
    data: data
});



回答3:


Just call this fun() function. And it will clear everything inside. Everything is documented here. A working jsfiddle here

<button onclick="fun()">
  Click
</button>

<script>
// create select2 option
$("#example").select2();

// the clearing function
function fun() {
    $("#example").select2().val(null).trigger("change");
}
</script>



回答4:


This worked for me!

$("#example").select2().val(null).trigger("change");


来源:https://stackoverflow.com/questions/34962269/jquery-select2-refresh-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!