If there is an input, there should be a form
This post was originally published on https://tomekdev.com/posts/input-and-form. Go there to read a bit more interactive and style richer version ✌️
I often see in Single Page apps a situation where someone uses just an <input>
field. Sometimes in the accompaniment of<label>
if you happen to work with a pro 🌟. It feels that when we gained control of inputs with two-way binding and we started handling onclick
events on buttons with our fancy frameworks, we forgot the old way of doing things.
The old way, and the right way
The headline of this section may suggest that the old way and the right way are two different things. Where in fact, it’s the opposite. If you come back with your memory before the frameworks (or ajax) era you see that people were using a <form>
element when dealing with inputs and buttons.
In the past we were extensively using <form method="">
to process the input. I encourage you to still use a form element. It comes with benefits.
Common mistake
I use the keyboard to navigate and interact with pages. That speeds up everything. So for me one of the biggest pitfalls of using <input>
without a <form>
is that the input is not auto-submittable, so to say.
When you hit ENTER
in the field that is inside the form then the form is submitted. That's very convenient for solo-input interfaces like a modal below:
You don’t have to touch your mouse or touchpad and click Save
button 🎉. That would be a waste of time!
Solution
It’s a common mistake to bind your action to a <button>
where in fact all you have to do is wrap your<input>
with a <form>
and assign submit
event to a form:
HTML file:
<form id="my-form">
<input name="example" type="text" />
<button type="submit">Submit</button>
</form>
Javascript:
const form = document.getElementById('my-form');form.addEventListener('submit', function handleSubmit(event) {
alert('Submit clicked');
event.preventDefault();
});
Don’t forget to prevent default behavior from firing and run your custom behavior. It could be running validation and actually sending the data.
One more thing that you should consider is always specifying the button’s type. It’s submit
by default in most browsers but Internet Explorer is different in this case and has button
as a default type.