Created
October 17, 2013 16:14
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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