12 August 2015

In our backend, we’re heavily relying on select2 for choosing values from a list in forms. Sometimes we want to show a list of existing values, but still allow the user to add his own. This can easily be done like this:

// make sure you've loaded jquery & select2 - http://select2.github.io/select2/
$(function() {
// choosing from a list of existing values in a textbox, with the option to add a new one
$('.select2-values:not(.no-select2)').each(function() {
var $this = $(this),
choices = $this.data('values');
$this.select2({
allowClear: true,
placeholder: ' ', // non-blank for allowClear to work
data: choices.map(function(c) {
return {id: c, text: c, new: false};
}),
createSearchChoice: function(c) {
return {id: c, text: c+" (new value)", new: true};
},
createSearchChoicePosition: 'bottom',
formatResultCssClass: function(c) {
return c.new ? 'select2-result-freeform' : '';
}
});
});
});

In our ingredient edit form it looks like this:

screenshot