Sometimes when using the Select2 plug-in, you will encounter this requirement: Select some data at once, then automatically select related items based on the data, I also meet this requirement and implement, here is a brief talk about my practice:
1. First I modified the source code of the Select2, added a method paste and added a custom method to the Allowedmethod array
Paste:function (items,selid) {
var datas = This.opts.data;
var values=[];
var max = this.opts.maximumSelectionSize;
for (var i=0;i<datas.length && values.length<max;i++) {
var data=datas[i];
for (Var j=0;j<items.length;j++) {
var item = Items[j];
var text = Data.text;
Text = Text.trim ();
Text = text.substring (0,text.length-1);
if (Text = = Item) {
var sel = {};
Sel.text = Data.text;
Sel.id = data.id;
Values.push (SEL);
}
}
}
if (Values.length >0) {
$ (selid). Select2 (' data ', values);
}
},
allowedmethods = ["Findhighlightablechoices", "paste", "Val", "Destroy", "opened", "open", "close", " Focus "," isFocused "," Container "," dropdown "," Onsortstart "," Onsortend "," Enable "," Disable "," ReadOnly "," Positiondropdown "," Data "," Search "," highlight "],
2. Capture the Paste event, then pass the Clipboard data to the custom paste method, and complete the selection of the data item in the Paste method
Because Select2 overloads the Select element, the actual operation is the element created by the Select2 plugin of the operation, and the author defines the Select2 element ID as Multiple-import-orgid,s2id_ Multiple-import-orgid is the Select element ID created by the Select2 plugin
$ ("#s2id_multiple-import-orgid"). On (' Paste ', function (e) {
//
var data;
if (window.clipboarddata) {
IE browser
data = Window.clipboardData.getData (' Text ')
}else{
Firefox,chrome Browser
data = E.originalevent.clipboarddata.getdata ("Text/plain");
}
var items = data.split (', ', maxorg); The option spacer where the number is a convention
$ (selid). Select2 ('paste', items,selid); Selid for Select2 plugin ID
});
With the code above, I believe we have understood the principle.