Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing event data in JavaScript via a string to dictate which input forms to be captured

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?

like image 264
Aero Avatar asked Jan 23 '26 16:01

Aero


1 Answers

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 protected]">
  <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 protected]">
  <br>
  <input type="submit" value="Submit">
</form>
like image 54
T.J. Crowder Avatar answered Jan 25 '26 07:01

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!