0

I have a two dropdowns that use Select2.js.

The second dropdown will initiate an ajax call base on the value from the first dropdown.

Assuming that I have already the result that I needed from Ajax call, and I already know what will be the result and that is the value 1276 and 1277.

What I want is when I click either one of the results all the results will be selected.

As what I read in Neelu's answer this will supposed to do the trick:

//this code block is outside the ajax call of select2.js

$('.select-2').on('select2:select', function() {
    $('.select-2').val([1276,1277]);
    $('.select-2').trigger("change");
});

The result doesn't reflect in the Select2 element but when I check the value using .val(), I get the result 1276 and 1277.

What I noticed if I trigger a different event e.g. button click to get the value of the Select2. That's the time it will work, but when I trigger another Select2 ajax call it doesn't work again.

threeFatCat
  • 840
  • 13
  • 30

1 Answers1

0

I found the solution:

This is because during ajax call if there are no selected options, and there are no option tag generated yet, thus Select2.js can't reflect the changes in the display even though .trigger('change') was already set.

So the trick is, during ajax call, once you received the response create an option tag (which is in my case I already knew that the response will be two value and I also want to select both of them either which I selected) thus I create two option tag after ajax call:

//..Ajax code response....
var selectElement = $(this)[0].$element[0];
processResults: function (data) {
    $.each(data, function( k, v ) {
        selectElement.innerHTML += '<option value="'+v.id+'">'+v.text+'</option>';
    });
}

Then outside your ajax code:

$('.select-2').on('select2:select', function() {
    $('.select-2').val([1276,1277]).trigger("change");
});

If you want to remove both selections if you either unselect one of them, this is the trick:

$('.select-2').on('select2:unselect', function() {
    $('.select-2').val('').trigger("change");
    //then destroy the option tag pre-created during ajax call
    $('.select-2').empty();
});
threeFatCat
  • 840
  • 13
  • 30