Search code examples
jqueryasp.net-mvcjquery-select2jquery-select2-4

JQuery Select2 - Re initialization with data not working


I am trying to replace data populated on page load via razor. I have three select2 comboboxes, Region, Clients and Issues. Region filters clients. I use the jquery select2 pluging on these comboboxes. I instantiate them on documet.ready. By default Clients just shows all the clients. DropDowns.Clients is a universal list that contains the dropdown data.

$("#selectRegion").select2({
    placeholder: "Filter By Region",
    allowClear: true,
    width: '100%'

}).on("change", function (e) {

    debugger;
    var data = [];

    var regionID = $(this).val();

    $.each(DropDowns.Clients, function (idx, item) {
        if (item.regionID == regionID)
            data.push({ "id": item.clientID, "text": item.Name });
    })


    $("#selectClient").select2({
        data: data
    });

    debugger;
});


$("#selectClient").select2({
    placeholder: "Filter By Client",
    allowClear: true,
    width: '100%'

}).on("change", function (e) {

});

The function fires when I change the checkbox and the data array gets populated with the correct data but if I then set the data attr nothing changes. I have read through the currrent solutions on Stack Overflow but so far none oof them has worked so I think a second pair of eyes might do the trick. I am using v4 select2 should I consider going back to 2? Any help will be appreciated.


Solution

  • I manage to solve the Issue with the following.

    //Clear List
    $("#selectIssue").select2().empty()
    
    $("#selectIssue").select2({
        data: data,
        placeholder: "Filter By Issue",
        allowClear: true,
        width: '100%'
    })