Skip to content

Instantly share code, notes, and snippets.

@thpoiani
Created May 8, 2014 04:42
Show Gist options
  • Save thpoiani/344ed2ddf666c8e93b0c to your computer and use it in GitHub Desktop.
Save thpoiani/344ed2ddf666c8e93b0c to your computer and use it in GitHub Desktop.
Get object from array inputs - native way to serialize a form
<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>
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"
// }
@formariz
Copy link

Change this:

fields = document.querySelectorAll('input[name^=user], textarea[name^=user]');

for this:

fields = document.querySelectorAll('[name^=user]');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment