Created
January 22, 2012 04:51
-
-
Save bbqsrc/1655648 to your computer and use it in GitHub Desktop.
getFormData method
This file contains 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
/* | |
Example HTML: | |
<form name="form" id="form"> | |
<fieldset name="first"> | |
<div> | |
<fieldset name="second"> | |
<div> | |
<label>Test <input name="test" value="data!"></label> | |
<label>Tick <input name="tick" type="checkbox" checked="checked"></label> | |
</div> | |
</fieldset> | |
</div> | |
</fieldset> | |
</form> | |
Example JS: | |
>>> var res = getFormData('#form'); | |
>>> console.log(res.form.first.second.test); | |
"data!" | |
>>> console.log(res.form.first.second.tick); | |
true | |
*/ | |
function getFormData(form) { | |
var obj = {}, i, ii, j, jj, parents, current; | |
inputs = $(form).find('input'), input; | |
for (i = 0, ii = inputs.length; i < ii; ++i) { | |
input = $(inputs[i]); | |
parents = input.parents('fieldset, form').toArray().reverse(); | |
current = obj; | |
for (j = 0, jj = parents.length; j < jj; ++j) { | |
if (current[parents[j].name] == null) { | |
current[parents[j].name] = {}; | |
} | |
current = current[parents[j].name]; | |
} | |
if (input[0].type == "checkbox") { | |
current[input[0].name] = input[0].checked; | |
} else { | |
current[input[0].name] = input.val(); | |
} | |
} | |
return obj; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment