Created
August 15, 2017 17:17
-
-
Save DennisMartinez/2117d53c262017d9d8d63aa73882fde6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| <form> | |
| <div><input type="text" name="first.name"></div> | |
| <div><input type="text" name="middle.name" value="ds"></div> | |
| <div><input type="text" name="last.name"></div> | |
| <div><label><input type="checkbox" name="language" value="english" checked> English</label></div> | |
| <div><label><input type="checkbox" name="language" value="russian" checked> Russian</label></div> | |
| <div>Gender:</div> | |
| <div><label><input type="radio" name="gender" value="male" checked> Male</label></div> | |
| <div><label><input type="radio" name="gender" value="female"> Female</label></div> | |
| </form> |
This file contains hidden or 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
| // Not required but may be useful. Generally bad practice to extend from native methods. | |
| // | |
| // To use: document.querySelector('your-form').serialize() | |
| HTMLElement.prototype.serialize = function() { | |
| return serialize(this) | |
| } | |
| console.log(serialize(document.querySelector('form'))) | |
| console.log(document.querySelector('form').serialize()) |
This file contains hidden or 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
| function serialize(form) { | |
| const formData = new FormData(form) | |
| let formKeys = [...formData.keys()] | |
| // Let's remove duplicates | |
| formKeys = [...new Set(formKeys)] | |
| return formKeys.map(name => { | |
| let values = [...formData.getAll(name)] | |
| let camelName = name.toLowerCase() | |
| .replace(/[^A-Za-z0-9]/g, ' ').split(' ') | |
| .reduce((piece, word) => piece + (word.charAt(0).toUpperCase() + word.slice(1))) | |
| if (values.length <= 1) values = values[0] | |
| return { | |
| [camelName]: name, | |
| value: values | |
| } | |
| }) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment