JS: DOM API
Theory: Forms
There are two approaches to working with forms in modern front-end applications.
Sometimes, data on the page changes immediately as the form changes. These forms don't have any Save or Send buttons. Each form element is associated with a handler that tracks any changes. A typical example could be filtering data on a page.
In a more classic version, we send the form with a button. In this case, you need to use the submit form event:
Why not put a click event on the form submit button? Technically, we can do it, but it'll break the standard behavior. Browsers allow you to send forms from the keyboard by pressing the Enter key. Here, we send forms without pressing a button.
Processing the form is usually set up like this:
- The data from the form are extracted
- A request is made to the server / Data in the application are changed
- The appearance changes
We'll look at the second and third points in future lessons when we discuss AJAX. Here we'll talk about the first. How to get the form data.
There are two approaches: the right one and the wrong one. Let's look at the wrong one:
With this approach, you need to work with each form element individually. First, extract it from the DOM, then collect the values. There's no need to do this, however; you can do it correctly instead.
The correct way is to use a FormData object, which is available in the browser:
Extracting form elements
Sometimes, however, you have to access the form elements directly when we implement validation while changing the form, not when we send it.
In such cases, work with the elements of the form goes directly:
If there are a lot of elements, then the code executing queries in the DOM will get cumbersome. We can avoid it by using the DOM features related to forms.
Each form contains the elements property, which returns an object with all elements of that form. The object keys are the names of the elements, and the values are the elements themselves:
Recommended programs
Completed
0 / 18

