public
Last active

  • Download Gist
jsonForm.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
(function($){
 
var merge = function(merged, source){
for(var property in source) {
if( typeof source[property] === "object" &&
typeof merged[property] !== "undefined") {
merge(merged[property], source[property]);
} else {
merged[property] = source[property];
}
}
return merged;
};
 
var build = function(name, value){
 
return (function gerarJSON(json, name, value){
 
var hierarquia = name.split(".");
var propriedade = hierarquia.shift();
json[propriedade] = (hierarquia.length > 0)?
gerarJSON({}, hierarquia.join(".", value)):value;
 
return json;
 
})({}, name, value);
 
}
 
$.fn.extend({
getJSON: function(){
var json = {};
$(this).find("input,select,textarea")
.each(function(index, input){
var parcial = build( $(input).attr("name"), $(input).val());
merge(json, parcial);
});
return json;
}
});
 
})(jQuery);
 
$("form").getJSON()

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.