3

I'm currently creating a feature for an application which allows users to create custom forms. This renders fine, however my issue lies in capturing the information after the form is submitted.

For the sake of this question let's say I have an array of input names (as strings).

['firstName', 'lastName', 'emailAddress']

Upon submission I need to loop through the array and use the strings to determine the target elements to grab the values from.

e.target.'array string'.value;

How can I do it?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aero
  • 317
  • 1
  • 4
  • 15
  • Is `e.target` the `form` ? Is `firstName` `name` attribute of element ? Can you include `html` at Question ? Are the values not currently accessible at `form` submission ? – guest271314 Mar 19 '16 at 18:11
  • yes, e.target is the form and 'firstName' is the name value. – Aero Mar 19 '16 at 18:12

1 Answers1

3

Forms have an elements collection which is an HTMLFormControlsCollection keyed by name. So assuming e.target is the form (e.g., this is a submit event);

e.target.elements[someVariable].value;

Live example:

document.querySelector("form").addEventListener("submit", function(e) {
  e.preventDefault();
  var elements = e.target.elements;
  ['firstName', 'lastName', 'emailAddress'].forEach(function(name) {
    console.log(name + ": " + elements[name].value);
  });
});
<form>
  <input type="text" name="firstName" value="The first name">
  <input type="text" name="lastName" value="The last name">
  <input type="email" name="emailAddress" value="email@example.com">
  <br>
  <input type="submit" value="Submit">
</form>

Alternately, the more general solution is querySelector:

e.target.querySelector('[name="' + someVariable + '"]').value;

Live example:

document.querySelector("form").addEventListener("submit", function(e) {
  e.preventDefault();
  var form = e.target;
  ['firstName', 'lastName', 'emailAddress'].forEach(function(name) {
    console.log(name + ": " + form.querySelector('[name="' + name + '"]').value);
  });
});
<form>
  <input type="text" name="firstName" value="The first name">
  <input type="text" name="lastName" value="The last name">
  <input type="email" name="emailAddress" value="email@example.com">
  <br>
  <input type="submit" value="Submit">
</form>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875