jquery select2 刷新数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34962269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:01:18  来源:igfitidea点击:

jquery select2 refresh data

jqueryjquery-select2

提问by Thang Le Sy

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

select2用来选择和ajax加载数据,当初始选择后状态改变时如何替换旧数据。

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");
        });
    });

回答by Federico Baron

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

在更新数据之前尝试清空 select2 选项,这是因为默认情况下它会将数据附加到现有选项。

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

回答by Evan Hsu

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

回答by pankaj

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

只需调用此 fun() 函数即可。它会清除里面的一切。一切都记录在这里这里有一个有效的jsfiddle

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

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

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