dynamicdropdown-aromn
Version:
This is a simple plugin that allows a dropdown be feeded by json data from URL get response.
48 lines (36 loc) • 1.69 kB
JavaScript
(function($) {
$.fn.dynamicDropdown = function(options) {
// Defining default settins for the plugin.
var settings = $.extend({
url: '',
}, options);
if ( $(this)[0].tagName != 'SELECT' )
{
console.log('ERROR: Target is not a select object');
return false;
}
if ( $(this)[0].className != 'form-control' ) {
$(this).addClass('form-control');
}
// Create variable to reference 'this' object and use it later.
let this_obj = $(this);
// If the url was not defined or is empty, it raises an error and exits the execution.
if (!settings.url || settings.url == '') {
console.log('%c ERROR: Please provide an URL in the settings of the dropdown', 'background: red');
return false;
}
// AJAX call to the url provided in the plugin's settings.
$.getJSON(settings.url, function(result) {
// If the returned data is a JSON object, it proceeds to build the dropdown
// IMPORTANT: It relies on the structure of the JSON object returned.
$.each(result, function(i, value) {
// Appending data to the dropdown referenced by the variable this_obj
this_obj.append('<option>' + value.something + ' - ' + value.somethingelse + '</option>');
});
// If the call to the URL don't return a json object, it returns an error.
}).fail(function() {
console.log('%c ERROR: ' + 'Response data from ' + settings.url + 'is not a JSON object',
'background: red');
})
};
}(jQuery));