Form Events
submit
event
Form submission occurs when you click on a button with the type ="submit"
attribute or press the Enter
in any of its text fields. The submit
event can be used to validate (check) a form before submitting, since the event object has many useful properties associated with form elements. Submitting the form reloads the page, so remember to cancel the default action with the preventDefault()
method.
The elements
property of the form’s DOM element contains an object with references to all its elements with the name
attribute. Therefore, in the example, you get the value of the fields by referring to login.value
and password.value
.
change
event
Occurs after a form element has changed. For text fields or textarea
, the event will not occur every time a character is entered, but when focus is lost, which is not always convenient. For example, while you are typing something in the text field, there is no event, but as soon as the focus is gone, the change
event will occur. For other elements, for example select
, checkboxes and radio buttons, the change
event is triggered immediately after a value is selected.
Note the useful properties when working with the <select>
element in the example. Figure out what is stored in the value
, selectedIndex
and options
properties.
input
event
Occurs only in text fields and textarea
, and it is generated every time the element value changes, without waiting for focus to be lost. In practice, input
is the most important event for working with form text fields.
focus
and blur
events
Elements receive focus on mouse click or Tab
key. The moment of receiving and losing focus is very important, as when focusing, you can load data for autofill, start tracking changes, etc. When focus is lost, you can check the entered data.
When an element is focused, the focus
event occurs, and when focus is lost, for example, the user clicks elsewhere on the screen, the blur
event is called. You can activate or cancel focus programmatically by calling the focus()
and blur()
methods for the element in your code.
Only one page element can be in focus at a time, and the current element in focus is available as document.activeElement
.
Many elements cannot receive focus. For example, if you click on <div>
, it will not be in focus because it is not an interactive element.