The select2 plugin is great and works quite well for non-repeated items. However if you want to allow the user to select the same item multiple times then you might get into trouble (as I did).
select2 was not built with this idea of duplicated items in mind but since I needed it I had to hack this concept into it :)
I use a hidden field to keep track of the duplicated items. I prefered not to alter the way select2 handles his data structure and treats duplicates as it would have caused too many changes.
The hidden field is called "[id of your control]-selection-no-filter"
To enable repeated items, set the allowRepetitionForMultipleSelect property to true when calling select2 on an HTML control
Works with select HTML tags and hidden input
You can preload data using the selectedItemsForMultiple attribute
Why there is no nice and elegant solution? select2 uses the select HTML element to keep track of selected options. So every time a new value is selected, the setVal (select2, see below) method is called which in turns calls the val (jQuery) method on the select HTML element. If a value is selected twice or more then the val method will select the same option again and keep no information regarding how many times it was selected and in which order.
The way select2 stores selected options could be altered but that would introduce too many changes for such a trivial requirement.
// multi
setVal: function (val) {
var unique;
if (this.select) {
this.select.val(val);
} else {
unique = [];
// filter out duplicates
$(val).each(function () {
if (indexOf(this, unique) < 0) unique.push(this);
});
this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
}
}
Allow items to be repeated (select tag)
Default behavior i.e. no repetition (select tag)
Allow items to be repeated with preselection (hidden input)