Last active
March 2, 2017 21:37
-
-
Save zamicol/852505409b18d3da54c9d64f827d224a to your computer and use it in GitHub Desktop.
Simple Ajax with New Option for Select2 4
This file contains 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 initSelect2() { | |
$('.select2picker').select2({ | |
ajax: { | |
url: "", //put the RUL here. | |
dataType: 'json', | |
delay: 50, | |
data: function(params) { // Build the search URL | |
return { | |
filter: params.term // Search term, in this case "filter". | |
}; | |
}, | |
processResults: function(data) { | |
if (!data) { | |
console.log("No data returned on Ajax call.") | |
return {results: []}; | |
} | |
var returning = []; | |
data.forEach(function(element) { | |
var obj = {} | |
obj.id = element.id; | |
obj.text = element.id; | |
returning.push(obj) | |
}); | |
console.log(returning) | |
return { | |
results: returning; | |
}; | |
} | |
}, | |
tags: true, | |
// Allows user created new options. Needs tag set to true. | |
createTag: function(params) { | |
return { | |
id: params.term, | |
text: params.term, | |
newOption: true | |
} | |
}, | |
// New tag. | |
templateResult: function(data) { | |
var $result = $("<span></span>"); | |
$result.text(data.text); | |
if (data.newOption) { | |
$result.append("<em>(new)</em>"); | |
} | |
return $result; | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment