- Form properties and methods
- Navigation: form and elements
- Backreference: element.form
- Form elements
- input and textarea
- select and option
- new Option
- References
- Summary
- Document: forms property
- Value
- Examples
- Getting form information
- Getting an element from within a form
- Named form access
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- 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
Form properties and methods
Forms and control elements, such as have a lot of special properties and events.
Working with forms will be much more convenient when we learn them.
Navigation: form and elements
Document forms are members of the special collection document.forms .
That’s a so-called “named collection”: it’s both named and ordered. We can use both the name or the number in the document to get the form.
document.forms.my; // the form with name="my" document.forms[0]; // the first form in the document
When we have a form, then any element is available in the named collection form.elements .
There may be multiple elements with the same name. This is typical with radio buttons and checkboxes.
In that case, form.elements[name] is a collection. For instance:
These navigation properties do not depend on the tag structure. All control elements, no matter how deep they are in the form, are available in form.elements .
A form may have one or many elements inside it. They also have elements property that lists form controls inside them.
There’s a shorter notation: we can access the element as form[index/name] .
In other words, instead of form.elements.login we can write form.login .
That also works, but there’s a minor issue: if we access an element, and then change its name , then it is still available under the old name (as well as under the new one).
That’s easy to see in an example:
That’s usually not a problem, however, because we rarely change names of form elements.
Backreference: element.form
For any element, the form is available as element.form . So a form references all elements, and elements reference the form.
Form elements
Let’s talk about form controls.
input and textarea
We can access their value as input.value (string) or input.checked (boolean) for checkboxes and radio buttons.
input.value = "New value"; textarea.value = "New text"; input.checked = true; // for a checkbox or radio button
Please note that even though holds its value as nested HTML, we should never use textarea.innerHTML to access it.
It stores only the HTML that was initially on the page, not the current value.
select and option
A element has 3 important properties:
- select.options – the collection of subelements,
- select.value – the value of the currently selected ,
- select.selectedIndex – the number of the currently selected .
They provide three different ways of setting a value for a :
- Find the corresponding element (e.g. among select.options ) and set its option.selected to true .
- If we know a new value: set select.value to the new value.
- If we know the new option number: set select.selectedIndex to that number.
Here is an example of all three methods:
Unlike most other controls, allows to select multiple options at once if it has multiple attribute. This attribute is rarely used, though.
For multiple selected values, use the first way of setting values: add/remove the selected property from subelements.
Here’s an example of how to get selected values from a multi-select:
new Option
In the specification there’s a nice short syntax to create an element:
option = new Option(text, value, defaultSelected, selected);
This syntax is optional. We can use document.createElement(‘option’) and set attributes manually. Still, it may be shorter, so here are the parameters:
- text – the text inside the option,
- value – the option value,
- defaultSelected – if true , then selected HTML-attribute is created,
- selected – if true , then the option is selected.
The difference between defaultSelected and selected is that defaultSelected sets the HTML-attribute (that we can get using option.getAttribute(‘selected’) , while selected sets whether the option is selected or not.
In practice, one should usually set both values to true or false . (Or, simply omit them; both default to false .)
For instance, here’s a new “unselected” option:
let option = new Option("Text", "value"); // creates
The same option, but selected:
let option = new Option("Text", "value", true, true);
Option elements have properties:
option.selected Is the option selected. option.index The number of the option among the others in its . option.text Text content of the option (seen by the visitor).
References
Summary
document.forms A form is available as document.forms[name/index] . form.elements Form elements are available as form.elements[name/index] , or can use just form[name/index] . The elements property also works for . element.form Elements reference their form in the form property.
Value is available as input.value , textarea.value , select.value , etc. (For checkboxes and radio buttons, use input.checked to determine whether a value is selected.)
For , one can also get the value by the index select.selectedIndex or through the options collection select.options .
These are the basics to start working with forms. We’ll meet many examples further in the tutorial.
In the next chapter we’ll cover focus and blur events that may occur on any element, but are mostly handled on forms.
Document: forms property
The forms read-only property of the Document interface returns an HTMLCollection listing all the elements contained in the document.
Note: Similarly, you can access a list of a form’s component user input elements using the HTMLFormElement.elements property.
Value
An HTMLCollection object listing all of the document’s forms. Each item in the collection is a HTMLFormElement representing a single element.
If the document has no forms, the returned collection is empty, with a length of zero.
Examples
Getting form information
doctype html> html lang="en"> head> title>document.forms exampletitle> head> body> form id="robby"> input type="button" onclick="alert(document.forms[0].id);" value="robby's form" /> form> form id="dave"> input type="button" onclick="alert(document.forms[1].id);" value="dave's form" /> form> form id="paul"> input type="button" onclick="alert(document.forms[2].id);" value="paul's form" /> form> body> html>
Getting an element from within a form
const selectForm = document.forms[index]; const selectFormElement = document.forms[index].elements[index];
Named form access
doctype html> html lang="en"> head> title>document.forms exampletitle> head> body> form name="login"> input name="email" type="email" /> input name="password" type="password" /> button type="submit">Log inbutton> form> script> const loginForm = document.forms.login; // Or document.forms['login'] loginForm.elements.email.placeholder = "test@example.com"; loginForm.elements.password.placeholder = "password"; script> body> html>
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 Jul 7, 2023 by MDN contributors.
Your blueprint for a better internet.
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
![](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)
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
![](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)
Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!
Socials
About Me
![](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)
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.