Skip to content

Instantly share code, notes, and snippets.

@AbraaoAlves
Created May 16, 2011 20:08
Show Gist options
  • Save AbraaoAlves/975241 to your computer and use it in GitHub Desktop.
Save AbraaoAlves/975241 to your computer and use it in GitHub Desktop.
Method to insert options in select tag from json object.[update performance]
///<summary> Sample: </summary>
///<code>
/// $.getJson("url", function(data){
/// //data : [{Value:1, Text: 'value 1', Selected:false},{Value:2, Text: 'value 2', Selected: true}]
/// $("#mySelect").loadOptions(data);
/// });
/// or
/// $.getJson("url", function(data){
/// //data : [{id:1, name: 'value 1'},{id:2, name: 'value 2'}]
/// $("#mySelect").loadOptions(data, {value: 'id', text: 'name'});
/// });
///</code>
(function($){
var _default = { value: 'Value', text: 'Text', selected: 'Selected' };
$.fn.clearOptions = function(){
return this.each(function() {
if (this.tagName == 'SELECT')
this.options.length = 0;
});
};
$.fn.loadOptions = function(json, options) {
options = $.extend(_default, options || {});
return this.clearSelect().each(function() {
if (this.tagName == 'SELECT') {
var select = $("<select>");
$.each(data, function(index, optionData) {
var option = $("<option></option>").attr("selected", optionData[options.selected]).html(optionData[options.text]);
option.val(optionData[options.value]);
select.append(option);
});
$(this).html(select.html());
}
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment