In this lesson, you'll use JavaScript to gain access to the elements on your form.
There are two main strategies for gaining access to the input values:
- using DOM methods such as
document.getElementById() - creating a
FormDataobject that will contain all of the key, value pairs in a generator
In this lesson, you will only be learning about the first strategy: DOM methods. The second strategy will be covered in an upcoming lesson.
Different Types of DOM Methods
For a sample form:
<form id="demo-form">
<label for="name">Name:</label>
<input id="name" name="name" />
<input type="submit" />
</form>
If you type "Nomad" into the text input, you could select the value in the input element in a few ways:
document.getElementById('name').value; // Nomad
const form = document.getElementById('demo-form');
form.getElementsByTagName('input')[0].value; // Nomad
document.querySelectorAll('#demo-form > input')[0].value; // Nomad
form.children[1].value; // Nomad
These methods are:
.getElementById()- selecting the element by itsidattributeform.getElementsByTagName()- selecting the children of the form element that areinputelements, and selecting the first one.document.querySelectorAll()- using a CSS selector string to select the input elements that are children of the element with theidofdemo-form, and again selecting the first one.form.children- to select the second child of the form element, as the first one is the label.
All of these ways assume that you have either given each input a sensible id or that your form is structured in a very specific way so that it's easy to navigate.
These methods can be quite tedious to use if your form is complex, however, so there is a way to generate a data structure with all the key, value pairs of the form.
For that though, you'll want to know about iterators, which is covered in the next lesson.
Summary: How to Access Input Values Using Javascript DOM Methods
You've just learned the basics of accessing form element values using JavaScript, which is a crucial step in mastering web form handling. In this lesson you:
- Became familiar with using
document.getElementById()to select elements directly by their uniqueidattribute for straightforward access. - Practiced selecting form inputs based on their relationship to other elements using methods like
form.getElementsByTagName(). - Practiced how to utilize
document.querySelectorAll()with CSS selectors to pinpoint form elements when you need more complex query capabilities. - Noticed that the
form.childrenproperty can be a quick way to reference form elements by their position in the DOM.
Remember, the strategies discussed here revolve around navigating the DOM to get values. In real-world applications, this may sometimes be less efficient, especially with bigger forms.
There are more sophisticated ways to handle form data, like using FormData objects, which you'll learn about soon.