I am using Select2 to manage large lists of data. Users have expressed a desire to be able to paste a list to the Select2 field in order to select various items at once instead of manually entering and matching each item in the list.
I have attempted to use tokenSeparators
to separate the items in the list. This and the demo on tokens in the documentation lead me to believe that what I am hoping to do is possible, but so far I have had no joy.
The code I use to instantiate Select2 is:
$('input').select2({
width: 'element',
matcher: function (term, text) {
return text.toUpperCase().indexOf(term.toUpperCase()) === 0;
},
minimumInputLength: 3,
multiple: true,
data: tagList, // tagList is an array of objects with id & text parameters
placeholder: 'Manage List',
initSelection: function (element, callback) {
var data = [];
$.each(function () {
data.push({id: this, text: this});
});
callback(data);
},
tokenSeparators: [',', ', ', ' ']
});
Just to clarify, in all other respects the select2 field works. It's just that nothing is matched when a list is pasted into the field. I would like to test all the items in the pasted list. Is this possible and, if so, how?
Edit: I have tried the following code but it does not seem to work:
$('body').on('paste', '#s2id_list-unitids .select2-input', function () {
var that = this;
setTimeout(function () {
var tokens = that.value.split(/[\,\s]+/);
$('#list-unitids').val(tokens, true);console.log($('#list-unitids').select2('val'));
}, 1);
});
And here is a fiddle I've created: http://jsfiddle.net/KCZDu/.