Skip to content

Instantly share code, notes, and snippets.

@Yaffle
Created August 11, 2011 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yaffle/1139221 to your computer and use it in GitHub Desktop.
Save Yaffle/1139221 to your computer and use it in GitHub Desktop.
// http://www.w3.org/TR/html5/association-of-controls-and-forms.html#concept-form-submit
// FormData (to support files?) FormData.append... (only POST + not string result???)
function serializeForm(form, submitter, useFormData) {
useFormData = useFormData && window.FormData;
var results = useFormData ? (new FormData()) : [], tagName, i, opts, j, field, elements = form.elements;
for (j = 0; j < elements.length; j++) {
field = elements[j];
tagName = field.tagName.toLowerCase();
if (tagName === 'object' || (tagName === 'input' && (field.type === 'image' || (!useFormData && field.type === 'file')))) {
return null;
}
if (!(field.disabled ||
!field.name ||
(tagName === 'input' && field.type === 'reset') ||
(tagName === 'input' && (field.type === 'checkbox' || field.type === 'radio') && !field.checked) ||
(tagName === 'input' && (field.type === 'button' || field.type === 'submit') && field !== submitter) ||
(tagName === 'button' && field !== submitter))) {
if (field.type === 'file' && tagName === 'input') {
for (i = 0; i < field.files.length; i++) {
results.append(field.name, field.files[i]);
}
} else {
opts = tagName === 'select' ? field.options : [{selected: 1, value: field.value}];
for (i = 0; i < opts.length; i++) {
if (opts[i].selected) {
if (useFormData) {
results.append(field.name, opts[i].value || '');
} else {
results.push(encodeURIComponent(field.name) + '=' + encodeURIComponent(opts[i].value || ''));
}
}
}
}
}
}
return useFormData ? results : results.join('&');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment