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
Solution 1:
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><inputtype="text"name="firstName"value="The first name"><inputtype="text"name="lastName"value="The last name"><inputtype="email"name="emailAddress"value="email@example.com"><br><inputtype="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><inputtype="text"name="firstName"value="The first name"><inputtype="text"name="lastName"value="The last name"><inputtype="email"name="emailAddress"value="email@example.com"><br><inputtype="submit"value="Submit"></form>
Post a Comment for "Accessing Event Data In Javascript Via A String To Dictate Which Input Forms To Be Captured"