Skip to content

Instantly share code, notes, and snippets.

@duncansmart
Created October 17, 2013 16:14
Show Gist options
  • Save duncansmart/7027773 to your computer and use it in GitHub Desktop.
Save duncansmart/7027773 to your computer and use it in GitHub Desktop.
Convert textbox to Select2 drop-down that allows new entries to be added (i.e. a combo box)
(function () {
var choices = [
"Foo",
"Bar",
"Baz"
];
$('#myTextBox')
.closest('.controls').append('<div class="help-block">Choose existing or type new one and press Enter</div>').end()
.select2({
width: 'resolve',
placeholder: " ",
initSelection: function (element, callback) {
var value = $(element).val();
if (value)
callback({ id: value, text: value });
},
query: function (query) {
// match
var items = $.grep(choices, function (item) {
if (!query.term)
return true;
return query.matcher(query.term, item);
});
items = items.sort();
if (query.term)
items.push(query.term);
// map to {id: '', text: ''}
var data = {};
data.results = $.map(items, function (item) {
return { id: item, text: item };
})
query.callback(data);
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment