Select2 Dropdown Multiple selection and deselection
I have a select2 with 4 code options:
<select id="ddlInqOn" class="InqSelect2 form-control"> <option value="1">--All--</option> <option value="2">Today Date</option> <option value="3">Past Date</option> <option value="4">Feature Date</option> </select> select2 called by this javascript :
$('.InqSelect2').select2({ dropdownAutoWidth: 'true', multiple: true }); I want to achieve, for example, when I click on all the parameters and then delete the other parameters, and if another option is selected, remove all the options from the selection.
I tried this code:
$('body').on('change', '#ddlInqOn', function() { debugger; // }); but the change event is not triggered, so any other way to track the change event of the select2 dropdown?
The answer to this question @Nimeksha works fine in jsfiddle given by @Nimeshka, but in my code I cannot get the trigger change event in the drop-down list and after searching I found a solution from here . the code is here:
$(document).on('change', '.InqSelect2', function () { debugger; if (e.params.data.id == 1) { $(this).val(1).trigger('change'); } else { values = $(this).val(); var index = values.indexOf('1'); if (index > -1) { values.splice(index, 1); $(this).val(values).trigger('change'); } } }); I also tried:
$('body').on('change', '.InqSelect2', function () { debugger; if (e.params.data.id == 1) { $(this).val(1).trigger('change'); } else { values = $(this).val(); var index = values.indexOf('1'); if (index > -1) { values.splice(index, 1); $(this).val(values).trigger('change'); } } }); but that will not work. also by id #ddlInqOn does not work.
Why the code above worked with $(document).on('change', '.InqSelect2', function () {}); worked, I don't know, but it works for me.
thanks again @Nimeshka
Select2 uses the jQuery event system. Therefore, you can attach to select2 events using the jQuery on method.
You can then set the value of the select element and fire the change event to refresh the selection window.
You can do what you requested as follows.
$('.InqSelect2').on('select2:select', function (e) { if (e.params.data.id == 1){ $(this).val(1).trigger('change'); }else{ values = $(this).val(); var index = values.indexOf('1'); if (index > -1) { values.splice(index, 1); $(this).val(values).trigger('change'); } } }); Note that I used '1' as the value of the -All-- option. Feel free to ask me if this is not clear to you.
https://jsfiddle.net/c6yrLoow/
Hope this helps :)