Macnux
Macnux

Reputation: 451

Repopulate select2 with data without losing selected index

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

Answers (2)

$.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

George Sharvadze
George Sharvadze

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

Related Questions