Should I put my input and button in a form?

·

3 min read

This is what I found myself trying to find out this week.

The set up

I have an input element and button. When you type in the input and press the button it goes and fetches data from an API, using what you type as a search. Well, it will eventually, for now it just does a bit of console logging.

HTML:

<input>
<button class="button">Submit</button>

JS:

const button = document.querySelector('.button')
button.addEventListener('click', function() {
  console.log('button clicked');
})

Test this code in CodePen

What is a form?

A form is used to submit data. So, for example, filling your name and email address on a website so the company will contact you. When the form is submitted it goes somewhere and does something.

In this example we're not sending the data off somewhere and we're not then giving users a message to confirm it's been sent. So therefore we don't need to put the input and button in a form because this isn't doing form-things.

The problem with not using a form

I wanted to test my EventListener, so I typed something in and pressed the Enter key on my keyboard, same as I would do if I saw a similar set up on any website. And nothing happened. It only gave me the console log when I actually clicked on the button.

Which makes sense: the event listener is listening to the button being clicked, not the enter key being pressed when the input is focused.

Maybe you're the sort of person who would automatically just click the button, which is great. But if you're the sort of person who presses enter when they've finished typing, then would you think to click the button or assume the site is broken?

The form solution

There are ways around this - you could listen for the enter key being pressed on the input, but that's a pain, because then you have to do something on a specific key being pressed. And also still listen for the button click.

The solution is to put the whole thing in a form and instead listen to the form being submitted.

HTML:

<form class="form">
  <input>
  <button type="submit" class="button">Submit</button>
</form>

JS:

const form = document.querySelector('.form')
form.addEventListener('submit', function(e) {
  e.preventDefault();
  console.log('button clicked');
})

Test this code in CodePen

Now when you press enter in the input box, it acts like you clicked the button.

You'll notice I also added an extra line in there:

e.preventDefault();

This is needed because a form wants to go somewhere, but we want to stay on the same page. preventDefault() tells it not to do the default form action.

Accessibility note

For ease of reading I haven't included any attributes on the input element. Nor did I include a label. A label is a good idea for accessibility: for more information read this very good guide on CSS tricks to labels and inputs