Created
May 8, 2014 04:42
-
-
Save thpoiani/344ed2ddf666c8e93b0c to your computer and use it in GitHub Desktop.
Get object from array inputs - native way to serialize a form
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
<form> | |
<label for="name">Name</label> | |
<input type="text" name="user[name]" id="name"> | |
<label for="email">Email</label> | |
<input type="email" name="user[email]" id="email"> | |
<label for="description">Description</label> | |
<textarea name="user[description]" id="description"></textarea> | |
<label for="password">Password</label> | |
<input type="password" name="user[password]" id="password"> | |
<input type="submit" value="Submit"> | |
</form> |
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
var user, fields; | |
user = {}; | |
fields = document.querySelectorAll('input[name^=user], textarea[name^=user]'); | |
for (var i = 0, length = fields.length; i < length; i++) { | |
var field, name, attr; | |
field = fields[i]; | |
name = field.name; | |
attr = name.substring(name.lastIndexOf('[') + 1, name.lastIndexOf(']')); | |
user[attr] = field.value; | |
}; | |
// user = { | |
// email: "[email protected]", | |
// name: "Thiago Henrique Poiani", | |
// description: "", | |
// password: "UrP7AnI55x9bVo9" | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Change this:
for this: