Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Forms

Forms are the main way to get data from the user: signing in, placing an order, searching, commenting. JavaScript intercepts the form submission, reads the fields, checks them and decides what to do next: show an error or send the data to the server.

The submit event

When the user clicks a button inside a form or presses Enter in a field, the form fires a submit event. By default the browser then reloads the page, so this behaviour is cancelled with the preventDefault() method:

<form>
  <input placeholder="Search">
  <button>Find</button>
</form>
 
<script>
  const form = document.querySelector('form');
 
  form.addEventListener('submit', (event) => {
    event.preventDefault();
    console.log('The form was submitted');
  });
</script>

Listen for the form's submit, not for a click on the button: that way Enter works too.

Reading fields

Fields get a name attribute, and then the form gives access to them by that name. A field's text is in value:

<form>
  <input name="city" value="Berlin">
  <button>Save</button>
</form>
 
<script>
  const form = document.querySelector('form');
 
  form.addEventListener('submit', (event) => {
    event.preventDefault();
    console.log(form.elements.city.value); // Berlin
  });
</script>

FormData

A FormData object collects all the form's fields at once. The Object.fromEntries() function turns it into a plain "name → value" object:

<form>
  <input name="name" value="Anna">
  <input name="email" value="anna@example.com">
  <button>Send</button>
</form>
 
<script>
  const form = document.querySelector('form');
 
  form.addEventListener('submit', (event) => {
    event.preventDefault();
    const data = Object.fromEntries(new FormData(form));
 
    console.log(data.name, data.email); // Anna anna@example.com
  });
</script>

Such an object is easy to send to the server with fetch().

Checkboxes and selects

For a checkbox what matters is not value but checked — true or false. For a select drop-down, value holds the value of the chosen option:

<form>
  <select name="size">
    <option value="s">Small</option>
    <option value="m" selected>Medium</option>
  </select>
  <label><input type="checkbox" name="gift"> Gift wrapping</label>
  <button>Order</button>
</form>
 
<script>
  const form = document.querySelector('form');
 
  form.addEventListener('submit', (event) => {
    event.preventDefault();
    console.log(form.elements.size.value); // m
    console.log(form.elements.gift.checked); // false
  });
</script>

Validating data

Before sending, data is checked, and if something is wrong a message is shown next to the form. The reset() method clears the form after a successful submission:

<form>
  <input name="password" type="password" placeholder="Password">
  <button>Sign in</button>
</form>
<p id="error"></p>
 
<script>
  const form = document.querySelector('form');
  const error = document.querySelector('#error');
 
  form.addEventListener('submit', (event) => {
    event.preventDefault();
    const password = form.elements.password.value;
 
    if (password.length < 8) {
      error.textContent = 'The password must be at least 8 characters long';
      return;
    }
    error.textContent = '';
    console.log('Signed in');
    form.reset();
  });
</script>

The browser can handle simple checks itself too — with the required and minlength attributes and type="email".

Common mistake

Forgetting that value is always a string, even for a type="number" field. Adding two fields glues the strings together:

<input id="a" type="number" value="2">
<input id="b" type="number" value="3">
 
<script>
  const a = document.querySelector('#a').value;
  const b = document.querySelector('#b').value;
 
  console.log(a + b); // 23
  console.log(Number(a) + Number(b)); // 5
</script>

Turn the value into a number with Number() before calculating, or use the valueAsNumber property.

Thanks for reading!

Donate to the site — we work hard for you.