select2: Pasting does not create the tags

Pasting a string like “marc,edward,jorge” does not create the tags.

$('#tagSelector').select2({
   tags: true,
   tokenSeparators: [','],
   multiple: true
});

Fiddle here:

http://jsfiddle.net/2wpjptuh/

Any idea on how to solve this?

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 28 (4 by maintainers)

Most upvoted comments

Doesn’t work here - reopen please.

Tried pasting with a@de.de,b@de.de,c@de.de (separator should be “,” )

@chrilehner I did it listening to onpaste event on select2’s text input (.select2-search__field). In the callback, i get clipboard content, append to it a tag separator, set it as the input value and trigger the keyup event.

That’s not the cleanest solution ever imagined but at least it is working without modifying the library.

For example (I used arrive.js here to watch for DOM changes)

$(document).arrive('.select2-search__field', {fireOnAttributesModification: true, existing: true}, function () {
	$(this).attr('onpaste', 'handleSelect2Paste.apply(this, arguments);');
});

Notice that I set event listener using the inline onpaste property : when I was doing it programmatically (addEventListener, or jQuery’s .on('paste',...)), my event listener was getting removed by select2 as soon as I selected an element or added a tag.

handleSelect2Paste = function(e){
	var separator = ' ';
	//get clipboard content in a cross-browser way
	var pastedText = '';
	if (window.clipboardData && window.clipboardData.getData) {
		pastedText = window.clipboardData.getData('Text');
	} else if (e.clipboardData && e.clipboardData.getData) {
		pastedText = e.clipboardData.getData('text/plain');
	}
	//stop propagation : we will trigger keyup manually
	e.preventDefault();
	e.stopPropagation();
	//append tag separator to clipboard content, set input value and trigger keyup on it
	$(this).val(pastedText + separator).trigger('keyup');
};