Reputation: 451
I have many select2
items on my page, which is all filled with items.
I add new data from a modal, and after modal closes I repopulate all select2
with the new data. I found that the select2
loses the selected value !!
This is the code I use:
$.get(callPath, { }, function(dataDropDown) {
$('.'+ refInput).each(function(){
$(this).html(dataDropDown);
$(this).trigger("change");
});
// $("'" + refInput + "'").html(dataDropDown);
})
I want to repopulate the elements without losing the selected value
Upvotes: 0
Views: 922
Reputation: 183
$.get(callPath, { }, function(dataDropDown) {
$('.'+ refInput).each(function(){
// get current value:
var selected = $(this).select2('val');
$(this).html(dataDropDown);
$(this).trigger("change");
// set it after repopulate:
$(this).select2('val', selected);
});
})
Upvotes: 1
Reputation: 570
You can pass the selected value in your Ajax request function. Something like this:
var selectedId = $('#myselect').val();
$.get(callPath, { }, function(dataDropDown, selectedId) {
$('.'+ refInput).each(function(){
$(this).html(dataDropDown);
$(this).trigger("change");
});
$('#myselect').val(selectedId);
// $("'" + refInput + "'").html(dataDropDown);
})
Upvotes: 0