Skip to content

Instantly share code, notes, and snippets.

@josue
Created November 18, 2011 22:03
Show Gist options
  • Save josue/1377918 to your computer and use it in GitHub Desktop.
Save josue/1377918 to your computer and use it in GitHub Desktop.
getInputs - collects and serialize all tag fields (input,textarea,select) into jQuery object or JSON format.
// prerequisites: jQuery library.
getInputs = function(t,f){
var opt = typeof t==="object" && t || {};
var target = opt.target || (t===jQuery || typeof t==="string") && t;
var filter = opt.filter || f;
var A = {
serialized: {},
fields: $("input,textarea,select", target || document)
};
A.fields = filter && A.fields.filter(filter) || A.fields;
A.fields.each(function(i,k){
var f = $(this).attr('name') || $(this).attr('id');
var val = $(this).val();
if(opt.clean && !val) { return null; }
if(this.type && (this.type=="checkbox" || this.type=="radio") && !this.checked) { f = null; }
if(f) {
if(f.match(/\[\]$/g)) {
var fa = f.replace("[]","");
if(!(A.serialized[fa] instanceof Array)) {
A.serialized[fa] = [];
}
A.serialized[fa].push(val);
}
else {
A.serialized[f] = val;
}
}
});
A.json = A.serialized;
return A;
};
// collect all document inputs and use as json format
var json_fields = getInputs().json;
if(fields.email) {
// logic here...
}
// collect and use jQuery objects
var jquery_fields = getInputs().fields;
if(jquery_fields.length) {
// logic
}
// use selector to collect inputs
var fields = getInputs("form#save_info").json;
$.post("/save/profile", fields);
// use selector (with filter) to collect inputs
// -- collects only fields with 'rel' attributes: <select rel='..'> <input rel='...'> , etc...
var fields = getInputs("form#save_info","[rel=required]").json;
$.post("/save/profile", fields);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment