How to add an additional selection in select2 multi select dropdown programmatically without losing the existing selected items

Viewed 175

I have a scenario like whenever a user selects a particular "State" in the multi-select select2 dropdown another state has to be automatically selected.

For example, if the user selects State 'A' then state 'C' also has to be selected. The logic is A & C always go together.

I am looking for an option to do this, currently, I am capturing select2:select event and checking the selected item is A or C, if so then getting all the selected items using

select2Object.select2('data')

Then loop through the items and getting the Value and then appending the value of state 'C' and then triggering the change event.

Is there any direct way to do this? For example, if I go with

select2Object.val("C"); 
select2Object.trigger('change'); 

this code then it will clear all other selections and select only the state 'C'. I am looking for a solution to add a new selection item without losing the old selected items.

1 Answers

This should be pretty straightforward. All you need to do is save the existing selections, push the new value, and trigger the change event. So for your case this should work:

// get all selected options (including the one you just selected)
let data = select2Object.val();

/* some logic that determines 'C' should be added */
data.push('C');
select2Object.val(data).trigger('change'); 
Related