Created
July 3, 2012 08:01
-
-
Save Onheiron/3038382 to your computer and use it in GitHub Desktop.
Gets datas form your HTML form and generates a JSON Object out of it!
This file contains hidden or 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 toJSON(node){ | |
if(!$(node).children().length) return $(node).val(); | |
var json = new Object(); | |
$(node).children('[name]').each(function(){ | |
if($(this).siblings("[name="+$(this).attr('name')+"]").length){ | |
if(!json[$(this).attr('name')]) json[$(this).attr('name')] = []; | |
json[$(this).attr('name')].push(toJSON(this)); | |
}else if($(this).children('[name]').length){ | |
json[$(this).attr('name')] = toJSON(this); | |
}else{ | |
json[$(this).attr('name')] = $(this).val(); | |
} | |
}); | |
return json; | |
} |
fixed code for better optimization. Iteration is now on children("[name]") so that only children with name attribute are iterated and the "has name" conditional can be deleted.
Here's one line compressed string:
function toJSON(a){if(!$(a).children().length)return $(a).val();var b=new Object;$(a).children("[name]").each(function(){e=$(this);c=e.attr("name");if(e.siblings("[name="+c+"]").length){if(!b[c])b[c]=[];b[c].push(toJSON(this))}else if(e.children("[name]").length){b[c]=toJSON(this)}else{b[c]=e.val()}});return b}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How To:
Write your HTML Form setting the name attribute for all the elements you want to put inside the JSON Object
Call the function with your Form's root as "node" parameter :
newJSON = fetch(formRoot);
Here you go! newJSON now contains all the datas in your form as well as its structure! Youre now ready to send this baby over to your server!