The HTML <form>
element is one of most important element which we are missing most in the modern web development framework such as React, Angular, Vue, etc., due to the onClick
event handler works fine. In this article I would like the explain a few important things about <form>
element which let you use the <form>
element from now.
What is form element
The HTML <form>
element used to define and wrap different kinds of form elements such as input, select., and used to collect user inputs for data processing and other purposes.
Available attributes for <form>
element
- accept-charset
- action
- autocomplete
- enctype
- method
- name
- novalidate
- target
I don't want to get into each of them. You can easily get the details of each from the internet. Let's go to the heart of our topic
The form element is semantic
The one of best reason to use <form>
element is, it is semantically meaningful to describe a form technically in the HTML though it doesn't change any appearance int he browser. This directly or indirectly helps in Web Accessibility.
The form element helps to submit the form without pressing submit button
Many keyboard lover may press the enter in the last input field which magically submits the form. But this is really because of the HTML <form>
element. On pressing enter in an input field of the form, the form submission goes to onSubmit
event handler and/or action
page defined in the form which help to submit the form quickly and easily. This behavior also helps people using Screen Reader and other assistive technologies to reduce the navigation
form with single and multiple input fields
The HTML <form>
element with single input field is doesn't required a <button>
or <input type='submit'>
to submit the form on pressing enter. Where as, <form>
with multiple input or other form elements requires <button>
or <input type='submit'>
to submit the form when pressing enter on one of the input field.
Note: The
<form>
element with onlyonSubmit
event handler will redirect the page if it notevent.preventDefault()
Form handling in Modern Web Application - Incorrect and Correct way
I would like to take React to showcase the incorrect and correct way of using the <form>
element.
The incorrect way:
const App = () => {
const handleSubmit = () => {
// Doing something here
}
return (
<div>
<input type="text" placeholder="Search here" />
<button onClick={handleSubmit}>Submit</button>
</div>
)
}
The correct way:
const App = () => {
const handleSubmit = () => {
// Doing something here
}
return (
<form>
<label htmlFor="search">Search</label> // Proper labelling and mapping it
to the corresponding form control
<input id="search" name="search" type="text" placeholder="Search here" />
<button type="submit" onClick={handleSubmit}>
Submit
</button>
</form>
)
}