Last active
June 15, 2019 15:01
-
-
Save dennohpeter/f2c0b746bc595aee39a110aa4e91e982 to your computer and use it in GitHub Desktop.
How to serialize form data with vanilla JS
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
/*! | |
* Serialize all form data into a query string | |
* (c) 2018 Chris Ferdinandi, MIT License, https://gomakethings.com | |
* @param {Node} form The form to serialize | |
* @return {String} The serialized form data | |
*/ | |
var serialize = function (form) { | |
// Setup our serialized data | |
var serialized = []; | |
// Loop through each field in the form | |
for (var i = 0; i < form.elements.length; i++) { | |
var field = form.elements[i]; | |
// Don't serialize fields without a name, submits, buttons, file and reset inputs, and disabled fields | |
if (!field.name || field.disabled || field.type === 'file' || field.type === 'reset' || field.type === 'submit' || field.type === 'button') continue; | |
// If a multi-select, get all selections | |
if (field.type === 'select-multiple') { | |
for (var n = 0; n < field.options.length; n++) { | |
if (!field.options[n].selected) continue; | |
serialized.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(field.options[n].value)); | |
} | |
} | |
// Convert field data to a query string | |
else if ((field.type !== 'checkbox' && field.type !== 'radio') || field.checked) { | |
serialized.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(field.value)); | |
} | |
} | |
return serialized.join('&'); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment