简体   繁体   English

如何在不丢失现有选定项目的情况下以编程方式在 select2 多选下拉列表中添加其他选择

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

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.我有一个场景,例如每当用户在多选 select2 下拉列表中选择特定的“状态”时,必须自动选择另一个状态。

For example, if the user selects State 'A' then state 'C' also has to be selected.例如,如果用户选择状态“A”,则还必须选择状态“C”。 The logic is A & C always go together.逻辑是A&C总是在一起。

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我正在寻找一个选项来执行此操作,目前,我正在捕获select2:select事件并检查所选项目是 A 或 C,如果是,则使用

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.然后循环遍历项目并获取值,然后附加状态 'C' 的值,然后触发更改事件。

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'.此代码然后它将清除所有其他选择并仅选择状态“C”。 I am looking for a solution to add a new selection item without losing the old selected items.我正在寻找一种解决方案来添加新的选择项而不会丢失旧的选择项。

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'); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM