i am using select 2 and problem is that it loads data accurately from ajax but when i press backspace or deselect an element in select it deselects all selected options in select. and i want to deselect just only last element on backspace and deselect specific element if i click on x button which is enabled when allowClear property
how to over come it cannot found in select2 documentation
here is the code of select 2 html
<Select id="SubServicesId" class="form-control" name="SubServicesId" multiple="multiple"></Select>
The Code for select2 is
function ApplySelect2ServicesConfiguration(select) {
//if ($(select).data('select2')) {
// $(select).select2('destroy');
//}
$(select).select2({
minimumInputLength: 1,
allowClear: true,
quietMillis: 100,
dropdownParent: $('#CheckInModal'),
id: function (repo) { return repo.Id; },
placeholder: {
// id: '-1', // the value of the option
text: 'Select Service'
},
ajax: {
url: "/Patients/GetSubServicesDDServerSide",
dataType: 'json',
delay: 300,
data: function (params) {
return {
q: params.term, // search term
page: params.page || 1,
PageSize: window.PageSize,
'departmentId': null,
'IndividualPackageId': $('#IndividualPackageId').val(),
PatientId: window.PatientId,
// ServiceAppointmentId: $('#HiddenServiveAppointmentId').val(),
// SubServiceIds: $('#HiddenSubServiceId').val(),
// PaymentNo: $('#HiddenLabPaymentNo').val(),
PanelOrganizationId: $('#CheckInPanelOrganizationId').val(),
PanelPackageId: $('#CheckInOnPanelOrganizationPackageId').val(),
SubServiceCategoryId: $("#SubServiceCategoryId").val(),
SubDepartmentsId: $("#SubDepartmentsId").val(),
};
},
processResults: function (data, params) {
params.page = params.page || 1;
for (i = 0; i < data.items.length; i++) {
data.items[i].text = data.items[i].Name.split(';')[0].split('--')[1]
data.items[i].id = data.items[i].Id
}
return {
results: data.items,
pagination: {
more: (params.page * window.PageSize) < data.total_count
}
};
},
cache: true
},
formatResult: function (element) {
return element
},
escapeMarkup: function (markup) {
return markup;
}, // let our custom formatter work
});
$(select).on('select2:select', function (e) {
var data = e.params.data;
});
$(select).on('select2:unselect', function (e) {
var unselectId = e.params.data.Id;
var selectedIds = $(select).val();
// Check if unselecting was initiated by a backspace key press
if (e.params.originalEvent.inputType === 'delete' && selectedIds && selectedIds.length > 1) {
// Manually remove the last selected item
selectedIds.pop();
$(select).val(selectedIds).trigger('change');
e.preventDefault();
}
});
}