- How to Get HTML Form Fields on Submit Event in JavaScript?
- Accessing Form Fields via HTMLFormElement.elements on Submit Event
- Directly Accessing Form Fields on Submit Event
- Javascript get all form fields
- # Table of Contents
- # Get all of a Form’s elements using JavaScript
- Get HTML Form Data In Javascript (Simple Examples)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- JAVASCRIPT GET FORM DATA
- EXAMPLE 1) GET FORM DATA & AJAX POST
- EXAMPLE 2) GET FORM DATA & URL PARAMS
- EXAMPLE 3) MORE FORM DATA
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- LINKS & REFERENCES
- INFOGRAPHIC CHEAT SHEET
- THE END
- Leave a Comment Cancel Reply
- Search
- Breakthrough Javascript
- Socials
- About Me
- FormData: getAll() method
- Syntax
- Parameters
- Return value
- Examples
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
How to Get HTML Form Fields on Submit Event in JavaScript?
Let’s suppose you have the following HTML element:
To get any field by its name or index (when a submit event is triggered), you can do any of the following:
Accessing Form Fields via HTMLFormElement.elements on Submit Event
When a submit event handler is attached to a element, event.target refers to the element itself. Therefore, you can access form fields by using their name or index on the HTMLFormElement.elements object (or the event.target.elements object in this case), for example, like so:
This works because the HTMLFormElement.elements property actually returns an HTMLFormControlsCollection object, which allows accessing of all the form fields contained within the element by using the element’s name and/or index.
The HTMLFormControlsCollection object also has the following methods for accessing form fields:
- HTMLFormControlsCollection.namedItem(name) (or HTMLFormElement.elements.namedItem(name) );
- HTMLFormControlsCollection.item(index) (or HTMLFormElement.elements.item(index) ).
The main difference between the two — i.e. accessing the form fields directly on the HTMLFormControlsCollection object versus doing so via the above-mentioned methods — is the fact that the former would return undefined if the element doesn’t exist, while the latter would return null .
Therefore, as an alternative, you can also access form fields via these methods as shown below:
Directly Accessing Form Fields on Submit Event
When a submit event handler is attached to a element, event.target refers to the element itself. Therefore, you can directly access the form fields by using their name or index directly on the event.target object, for example, like so:
This might not be the best approach as properties can get mixed up with other attributes specified on the element. Instead, using form.elements property might be a better approach as it only returns the form fields contained within the element.
Hope you found this post useful. It was published 14 Sep, 2022 . Please show your love and support by sharing this post.
Javascript get all form fields
Last updated: Jan 12, 2023
Reading time · 3 min
# Table of Contents
# Get all of a Form’s elements using JavaScript
To get all the elements in a form:
- Select the form element.
- Use the elements property to get a collection of the form’s elements.
- Optionally, convert the collection to an array using the Array.from() method.
Here is the HTML for the example.
Copied!DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> form id="my-form"> input type="text" id="first_name" name="first_name" /> input type="text" id="last_name" name="last_name" /> textarea id="message" name="message" rows="5" cols="30">textarea> input type="submit" value="Submit" /> form> script src="index.js"> script> body> html>
And here is the related JavaScript code.
Copied!const form = document.getElementById('my-form'); // ✅ Get all form elements const formElements = Array.from(form.elements); formElements.forEach(element => console.log(element); >); console.log('--------------------------'); // ✅ Get only the input elements in a form const onlyInputs = document.querySelectorAll('#my-form input'); onlyInputs.forEach(input => console.log(input); >);
We selected the form element using the document.getElementById() method.
Copied!const form = document.getElementById('my-form');
The elements property on the form returns a collection containing all of the form controls.
Copied!const form = document.getElementById('my-form'); // ✅ Get all form elements const formElements = Array.from(form.elements);
Get HTML Form Data In Javascript (Simple Examples)
Welcome to a quick tutorial on how to get the HTML form data in Javascript. So you have an HTML form but want to do the processing in Javascript instead?
- Create the HTML form as usual – Give the form an ID, and attach a name to the input fields.
- Create a form data object, and feed the HTML form in as a parameter.
- var form = document.getElementById(«demo»);
- var data = new FormData(form);
- Lastly, manually append more keys/values if required – data.append(«KEY», «VALUE»);
- Create a form data object, and feed the HTML form in as a parameter.
That covers the quick basics, but read on for more examples!
TLDR – QUICK SLIDES
TABLE OF CONTENTS
JAVASCRIPT GET FORM DATA
All right, let us now get into the examples of how to get the form data in Javascript.
EXAMPLE 1) GET FORM DATA & AJAX POST
- Create the HTML as usual.
- Create a new FormData(HTML FORM) object, and submit it to the server “as usual”.
EXAMPLE 2) GET FORM DATA & URL PARAMS
- (A & B1) The “usual HTML form” and create var data = new FormData(HTML FORM) .
- (B2) Then, “convert” into var params = new URLSearchParams(data) .
- (B3) Attach the parameters to the end of the URL – «http://site.com?» + params.toString() , and submit the form.
EXAMPLE 3) MORE FORM DATA
- (A) Take note that the HTML form now has a “custom widget”.
- (B1) Since the “custom widget” is not the usual , var data = new FormData(FORM) will not automatically adapt data from it.
- (B2) To “fix” that, we can use data.append(«KEY», «VALUE») to manually add more data entries.
- (B3) Now, the FormData object is not some “black hole”. You put data in and have no idea what’s inside.
- get(KEY) Returns the value of the specified KEY .
- has(KEY) Checks if the dataset contains KEY .
- key() Return all the keys in an array.
- values() Return all the values in an array.
- entries() Returns all the keys and values in an array.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
LINKS & REFERENCES
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
Leave a Comment Cancel Reply
Search
Breakthrough Javascript
Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!
Socials
About Me
W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.
Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.
FormData: getAll() method
The getAll() method of the FormData interface returns all the values associated with a given key from within a FormData object.
Note: This method is available in Web Workers.
Syntax
Parameters
A string representing the name of the key you want to retrieve.
Return value
An array of values whose key matches the specified name . Otherwise, an empty list.
Examples
If we add two username values to a FormData using append() :
.append("username", "Chris"); formData.append("username", "Bob");
The following getAll() method will return both username values in an array:
.getAll("username"); // Returns ["Chris", "Bob"]
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 7, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.