Skip to content

Instantly share code, notes, and snippets.

@ludovig
Created March 30, 2012 09:46
Show Gist options
  • Save ludovig/2250406 to your computer and use it in GitHub Desktop.
Save ludovig/2250406 to your computer and use it in GitHub Desktop.
Mootools way to retrieve forms values
/**
* Retrieve form values as an object
*
* Inspired by Element.toQueryString
* @see Dimitar Christoff response on http://stackoverflow.com/questions/2166042/how-to-convert-form-data-to-object-using-mootools
*
* @return object form
*
* @author Ludovic Vigouroux <ludovicv@theodo.fr> with the help of Fabrice Bernhard
* @since 2012-02-29
*/
Element.implement({
toJSON: function(){
var json = {};
this.getElements('input, select, textarea').each(function(el){
var type = el.type;
if (!el.name || el.disabled || type == 'submit' || type == 'reset' || type == 'file' || type == 'image') return;
var value = (el.get('tag') == 'select') ? el.getSelected().map(function(opt){
// IE
return document.id(opt).get('value');
}) : ((type == 'radio' || type == 'checkbox') && !el.checked) ? null : el.get('value');
Array.from(value).each(function(val){
// retrieve form
var reg = /[\W]+/g;
var form_names = el.name.split(reg);
form_names.pop(); // I dont find out why regex add an empty value
var form_graph = {};
var key = form_names.pop();
form_graph[key] = val;
var form = (function createArray(form_names) {
if (0 == form_names.length) {
return form_graph;
} else {
var key = form_names.pop();
old_form_graph = Object.clone(form_graph);
form_graph = {}
form_graph[key] = old_form_graph;
return createArray(form_names);
}
})(form_names);
Object.merge(json, form);
});
});
return json;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment