1
votes

I have a cascade Select2 ddl and when I select the master ddl, I populate the Detail ddl without no problem. On the other hand, when I select another item on master and then click the detail, at the first time the detail ddl lists the previous items just a miliseconds. So, I need to clear all of the list items besides the selected item when the main ddl's selected index changed. Is it possible? I have tried to all of the solution methods below, but they only clear the selected item. Any idea?

$('#ProjectId').select2('data', null);
$('#ProjectId').select2('data', { id: null, text: null })
$('#ProjectId').empty();
$('#ProjectId').val(null).trigger("change");
$("#ProjectId").remove();
$('#ProjectId').val('').trigger('change');


@Html.DropDownListFor(m => m.ProjectId, Enumerable.Empty<SelectListItem>(), "Select")


$(document).ready(function () {

    var issueType = $("#ProjectId");

    issueType.select2({
        allowClear: true,
        ajax: {
            url: '/Controller/GetProjects',
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    query: params.term, //search term
                    page: params.page,
                    id: selectedMasterId
                };
            },
            processResults: function (data, page) {
                var newData = [];
                $.each(data, function (index, item) {
                    newData.push({
                        id: item.Id,
                        text: item.Description
                    });
                });
                return { results: newData };
            },
            cache: true
        },
        escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
    }); 

});


$('#MasterId').change(function () {

    selectedMasterId = $(this).val();

        $('#ProjectId').select2('val', '');
        $('#ProjectId').select2('data', null);
    }
});
2
@AniketSahrawat Posted, thanks in advance...Jack
Which version of select2? (apparently there are some issues with v4)user3559349
Have a look at Sruit A.Suk's answer hereuser3559349
No time now - will take a look later.user3559349
Try $('#ProjectId').empty().trigger('change');user3559349

2 Answers

2
votes
$('#id').empty().trigger("change");

Where '#id' is the jQuery selector for your select2 element.

1
votes

On the select element put onchange="removeOthers(this)" in js code write this function:

function removeOthers(that){
    $('option', that).not(':eq(0), :selected').remove();
    //now refresh your select2
}