Skip to content

Instantly share code, notes, and snippets.

@mytory
Last active January 7, 2016 10:45
Show Gist options
  • Save mytory/9585bcf95f0731a8e949 to your computer and use it in GitHub Desktop.
Save mytory/9585bcf95f0731a8e949 to your computer and use it in GitHub Desktop.
/**
* Create Select2 library field that also can direct input.
* @param selector
*/
function direct_write_select2(selector){
$(selector).select2({
minimunInputLength: 1,
query: function(options){
var data = {results: []};
var dataSource;
var content = options.element.data('content');
if(content){
dataSource = content.split('|||');
// If visible text is value. e.g. <option>Strawberry</option>
_.each(dataSource, function(entry){
if(entry.toLowerCase().indexOf(options.term.toLowerCase()) > -1){
data.results.push({
id: entry,
text: entry
});
}
});
if(options.term){
data.results.push({
id: options.term,
text: options.term
});
}
}
dataSource = options.element.data('content-json');
if(dataSource){
// If visible text is differnt to value. e.g. <option value='3'>Strawberry</option>
_.each(dataSource, function(entry){
if(entry.text.toLowerCase().indexOf(options.term.toLowerCase()) > -1){
data.results.push({
id: entry.id,
text: entry.text
});
}
});
if(options.term){
data.results.push({
id: 0,
text: options.term
});
}
}
// Empty value.
data.results.push({
id: '',
text: '빈값' // 'Empty value' text
});
options.callback(data);
},
initSelection: function($el, callback){
callback({
id: $el.val(),
text: $el.val()
});
},
placeholder: '직접 입력 가능' // 'You can direct input' text.
});
if($(selector).val()){
$(selector).select2('val', $(selector).val());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment