Created
December 6, 2010 15:01
-
-
Save jarrettmeyer/730402 to your computer and use it in GitHub Desktop.
jQuery buildSelectList plugin
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 ($) { | |
$.fn.buildSelectList = function (options) { | |
defaults = { | |
url: null, // URL for the select list options. | |
data: null, // Data to be passed to the URL. | |
value: null, // Currently selected option value. | |
valueProperty: "value", // JSON property for option value. | |
textProperty: "text", // JSON property for option text. | |
type: "GET", // JSON HTTP method. | |
useCache: false, // Allow outputs to be cached. | |
emptyOption: true, // Should an empty select option be given? | |
emptyOptionText: "", // Empty select option text. (Only applies if emptyOption is true.) | |
spinner: null | |
}; | |
var opts = $.extend(defaults, options); | |
return this.each(function () { | |
var $selectElement = $(this), $spinner = $(opts.spinner); | |
var sl = { | |
htmlOptions: null, | |
initialize: function () { | |
sl.buildSelectList(); | |
sl.selectCurrent(); | |
}, | |
getJsonData: function () { | |
var jsonData; | |
$.ajax({ | |
url: opts.url, | |
data: opts.data, | |
async: false, | |
cache: opts.useCache, | |
dataType: "json", | |
type: opts.type, | |
success: function (json) { | |
jsonData = json; | |
} | |
}); | |
return jsonData; | |
}, | |
buildSelectList: function () { | |
// If the HTML options have already been built and no data object is being sent with the request, then | |
// return. There's no reason to build the select list again. | |
if (sl.htmlOptions && !data) { return; } | |
sl.showSpinner(); | |
var jsonData = sl.getJsonData(); | |
sl.htmlOptions = ""; | |
if (opts.emptyOption) { | |
sl.htmlOptions += "<option value=\"\">" + opts.emptyOptionText + "</option>"; | |
} | |
for (var i = 0; i < jsonData.length; i++) { | |
sl.htmlOptions += "<option value=\"" + jsonData[i][opts.valueProperty] + "\">" + jsonData[i][opts.textProperty] + "</option>"; | |
} | |
$selectElement.html(sl.htmlOptions); | |
sl.hideSpinner(); | |
}, | |
selectCurrent: function () { | |
$selectElement.val(opts.value); | |
}, | |
hideSpinner: function () { | |
if ($spinner) { | |
$spinner.hide(); | |
} | |
}, | |
showSpinner: function () { | |
if ($spinner) { | |
$spinner.show(); | |
} | |
} | |
}; | |
sl.hideSpinner(); | |
sl.initialize(); | |
}); | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment