Explore the basics of using forms in HTML and JavaScript
Forms are an extremely important part of HTML and Web platforms. They allow users to interact with the page, and
- Search for content on the site
- Trigger the filter to trim the result page
- send Message
there are more.
By default, the form submits its content to the server-side endpoint, which by default is the page URL itself:
<form>
...
<input type="submit">
</form>
We can setaction
The attributes of the form element, used bymethod
Attribute, default isGET
:
<form action="/contact" method="POST">
...
<input type="submit">
</form>
After clicking the submit input element, the browser sends a POST request/contact
URL on the same source (protocol, domain and port).
Using JavaScript, we can intercept this event and submit the form asynchronously (usingXHRwithBring it), we can also react to events that occur on a single form element.
Intercept form submission events
I just described the default behavior of forms without JavaScript.
In order to start using JavaScript to process forms, you need to interceptsubmit
Events on form elements:
const form = document.querySelector('form')
form.addEventListener('submit', event => {
// submit event detected
})
Now in the Submit event handler function, we willevent.preventDefault()
Ways to prevent default behavior and avoid form submission to reload the page:
const form = document.querySelector('form')
form.addEventListener('submit', event => {
// submit event detected
event.preventDefault()
})
At this point, clicking the "Submit Event" button in the form will not perform any action, except to provide us with controls.
Handling input element events
We can listen to many events in form elements
input
Triggered on the form element when the element value is changedchange
Triggered on the form element when the element value changes. In the case of textinput
Element andtextarea
, When the element loses focus, it will only be triggered once (not applicable to every single character typed)cut
Triggered when the user cuts text from a form elementcopy
Triggered when the user copies text from a form elementpaste
Triggered when the user pastes text into a form elementfocus
Triggered when a form element gains focusblur
Triggered when the form element loses focus
This is a sample form demonstration on Codepen:
Look at the penForm event demoBy Flavio Copes (@flaviocopes) InCipher pen.
Tech Wiki Online!