Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery select2 refresh data

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");
        });
    });
like image 867
Thang Le Sy Avatar asked Jan 23 '16 10:01

Thang Le Sy


Video Answer


2 Answers

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
});
like image 187
Federico Baron Avatar answered Nov 03 '22 18:11

Federico Baron


This worked for me!

$("#example").select2().val(null).trigger("change");
like image 32
Akintunde Akinfenwa Avatar answered Nov 03 '22 18:11

Akintunde Akinfenwa