# Forms

Reading what a visitor types, stopping a submit, and validation with one class.

Multimedia & Creative Technology · 2.1 Webcoding · Lesson 8 · version 2.0.1 · 2026-11-23

Tags: javascript, html, forms

Slides: <https://slides.mctantwerp.be/en/webcoding/06-forms>

Speaker notes: <https://slides.mctantwerp.be/en/webcoding/06-forms.notes.md>

<!-- slide 2 -->

## Agenda

1. Anatomy of a form
2. Reading the values
3. The submit event
4. Validation in HTML
5. Validation in JavaScript
6. validator--required
7. Exercises

<!-- slide 3 -->

## 1. Anatomy of a form

<!-- slide 4 -->

### Where the visitor talks back

- A login, a search bar, a newsletter, a checkout, a contact page.
- Everything else on a page goes one way. A form is where the visitor sends something back.
- HTML builds the fields and can send them without any JavaScript.
- JavaScript makes it pleasant: **feedback while you type**, a total that updates, a red border on the field that is wrong.

<!-- slide 5 -->

### Anatomy of a form

```html
<form>
  <label for="name">Name</label>
  <input id="name" name="name" type="text">
  <br>

  <label for="email">Email</label>
  <input id="email" name="email" type="email">
  <br>

  <button>Sign up</button>
</form>
```

<!-- slide 6 -->

### The elements

| Element | For |
| --- | --- |
| [<form>](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/form) | The box around the fields that are sent together |
| [<label>](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/label) | What goes in a field |
| [<input>](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input) | One line of input. The type decides which kind |
| [<textarea>](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/textarea) | Longer text, over several lines |
| [<select>](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/select) | A choice from a list, with an option per choice |
| [<button>](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/button) | Sends the form |

<!-- slide 7 -->

### The type does the work

```html
<input type="text" placeholder="text">
<input type="email" placeholder="email">
<input type="password" value="secret">
<input type="number" value="42">
<input type="date">
<input type="color" value="#cdeb32">
<input type="checkbox" checked>
<input type="range">
```

<!-- slide 8 -->

### Every field gets a label

```html
<label for="email">Email</label>
<input id="email" type="email">

<label>
  <input type="checkbox">
  I read the terms
</label>
```

1. `for` points at the `id` of the field.
2. A click on the label puts the cursor in the field.
3. Or put the field inside the label. Handy for a checkbox: the whole sentence becomes clickable.

<!-- slide 9 -->

### name is what gets sent

```html
<form action="/search">
  <input name="q" type="search">
  <input name="year" type="number">
  <button>Search</button>
</form>
```

Search for forms in 2026 and the browser goes to:

```text
/search?q=forms&year=2026
```

> [!NOTE]
> `id` is for the label, CSS and JavaScript. `name` is for the data.

<!-- slide 10 -->

## 2. Reading the values

<!-- slide 11 -->

### From the DOM lesson

#### index.html

```html
<input id="name">
<button id="greet">Greet</button>
<p id="output"></p>

<script src="script.js" defer></script>
```

#### script.js

```js
const nameInput = document.querySelector('#name');
const button = document.querySelector('#greet');
const output = document.querySelector('#output');

button.addEventListener('click', function () {
  output.textContent = 'Hello ' + nameInput.value;
});
```

<!-- slide 12 -->

### .value

```html
<input id="name" placeholder="Your name">
<button id="greet">Greet</button>
<p id="output"></p>

<script>
  const nameInput = document.querySelector('#name');
  const output = document.querySelector('#output');

  document.querySelector('#greet').addEventListener('click', function () {
    output.textContent = 'Hello ' + nameInput.value;
  });
</script>
```

*read on click*

```html
<input id="name" placeholder="Your name">
<button id="greet">Greet</button>
<p id="output"></p>

<script>
  const nameInput = document.querySelector('#name');
  const output = document.querySelector('#output');

  document.querySelector('#greet').addEventListener('click', function () {
    output.textContent = 'Hello ' + nameInput.value;
  });
</script>
```

*read too early*

```html
<input id="name" placeholder="Your name">
<button id="greet">Greet</button>
<p id="output"></p>

<script>
  const name = document.querySelector('#name').value;
  const output = document.querySelector('#output');

  document.querySelector('#greet').addEventListener('click', function () {
    output.textContent = 'Hello ' + name;
  });
</script>
```

<!-- slide 13 -->

### Always a string

```html
<input id="a" type="number" value="2">
<input id="b" type="number" value="3">
<button id="add">Add</button>

<script>
  const a = document.querySelector('#a');
  const b = document.querySelector('#b');

  document.querySelector('#add').addEventListener('click', function () {
    console.log(typeof a.value);
    console.log(a.value + b.value);
    console.log(Number(a.value) + Number(b.value));
  });
</script>
```

<!-- slide 14 -->

### Checkbox, radio, select

```html
<label><input id="terms" type="checkbox"> Terms</label>
<label><input class="size" type="radio" name="size" value="S"> S</label>
<label><input class="size" type="radio" name="size" value="M" checked> M</label>
<select id="drink">
  <option value="coffee">Coffee</option>
  <option value="tea">Tea</option>
</select>
<button id="show">Show</button>

<script>
  document.querySelector('#show').addEventListener('click', function () {
    console.log(document.querySelector('#terms').checked);
    document.querySelectorAll('.size').forEach(function (radio) {
      if (radio.checked) {
        console.log(radio.value);
      }
    });
    console.log(document.querySelector('#drink').value);
  });
</script>
```

<!-- slide 15 -->

### Through the form

```js
const form = document.querySelector('#signup');

form.email.value;
form.terms.checked;

document.forms.signup.email.value;
```

1. One querySelector for the whole form.
2. Every field is there under its `name` or its `id`.
3. `document.forms` lists every form of the page, by `id` or `name`. Old school, and still in a lot of tutorials.

<!-- slide 16 -->

### input or change

```html
<input id="name" placeholder="Type here">
<input id="volume" type="range">

<script>
  document.querySelectorAll('input').forEach(function (field) {
    field.addEventListener('input', function () {
      console.log('input', field.value);
    });
    field.addEventListener('change', function () {
      console.log('change', field.value);
    });
  });
</script>
```

<!-- slide 17 -->

### A counter while you type

```html
<style>.almost { color: red; font-weight: bold; }</style>

<label for="bio">Bio</label><br>
<textarea id="bio" maxlength="140" rows="3"></textarea>
<p id="count">0 / 140</p>

<script>
  const bio = document.querySelector('#bio');
  const count = document.querySelector('#count');

  bio.addEventListener('input', function () {
    count.textContent = bio.value.length + ' / 140';

    if (bio.value.length > 120) {
      count.classList.add('almost');
    } else {
      count.classList.remove('almost');
    }
  });
</script>
```

<!-- slide 18 -->

### An <input type="number"> holds 42. What is typeof field.value?

- A. 'number'
- B. 'string'
- C. 'object'
- D. It depends on the browser

**Answer:** B. 'string'

value is always a string, whatever the type of the field. Number(field.value) gives you a number to calculate with.

<!-- slide 19 -->

## 3. The submit event

<!-- slide 20 -->

### Listen to the form

#### Not this

```js
button.addEventListener('click', function () {
  // Enter in a field skips this
});
```

#### This

```js
form.addEventListener('submit', function () {
  // a click on the button
  // or Enter in any field
});
```

<!-- slide 21 -->

### What a submit does

```html
<form id="signup">
  <input name="name" placeholder="Your name">
  <button>Send</button>
</form>

<script>
  console.log('Page loaded', location.search);

  const form = document.querySelector('#signup');

  form.addEventListener('submit', function () {
    console.log('Submitted');
  });
</script>
```

<!-- slide 22 -->

### preventDefault

```html
<form id="signup">
  <input name="name" placeholder="Your name">
  <button>Send</button>
</form>
<p id="output"></p>

<script>
  const form = document.querySelector('#signup');

  form.addEventListener('submit', function (event) {
    event.preventDefault();
    document.querySelector('#output').textContent = 'Stopped!';
  });
</script>
```

<!-- slide 23 -->

### A button that does not send

| type | Inside a form it |
| --- | --- |
| `submit` | Sends the form. **The default**, also when you leave the type out. |
| `button` | Does nothing on its own. For anything your script handles. |

> [!WARNING]
> A `<button>` without a type inside a form sends it. Write `type="button"` on every other button.

<!-- slide 24 -->

### A form has a single button without a type. Somebody presses Enter in a text field. What happens?

- A. Nothing, Enter only works in a textarea
- B. The form is sent and the submit event fires
- C. Only a click event fires on the button
- D. The text field gets a new line

**Answer:** B. The form is sent and the submit event fires

Enter in a field sends the form, and a button without a type is a submit button. That is why you listen to submit on the form: it catches the click and the Enter.

<!-- slide 25 -->

## 4. Validation in HTML

<!-- slide 26 -->

### Client side, server side

#### In the browser

- HTML attributes and JavaScript, before anything is sent.
- **For the visitor:** the error shows up right away, on the field.
- Anybody can switch it off in the developer tools.

#### On the server

- The code that receives the data checks it again.
- **For your data:** the only check you can trust.
- Not in this course. In every backend you will ever write.

<!-- slide 27 -->

### Rules in an attribute

| Attribute | Rule |
| --- | --- |
| `required` | Not empty |
| `type="email"` | Looks like an email address |
| `minlength="8"` | At least 8 characters |
| `min="1" max="10"` | A number between two values |

<!-- slide 28 -->

### The browser checks

```html
<form id="signup">
  <input name="email" type="email" required placeholder="Email">
  <br>
  <input name="password" type="password" minlength="8" required placeholder="Password">
  <br>
  <button>Sign up</button>
</form>

<script>
  document.querySelector('#signup').addEventListener('submit', function (event) {
    event.preventDefault();
    console.log('Valid, so this runs');
  });
</script>
```

<!-- slide 29 -->

### When the bubbles are not enough

- They look like the browser, not like your site, and you cannot style them.
- They show one error at a time, and disappear after a few seconds.
- `novalidate` on the form switches them off.
- From then on your JavaScript does the checking, and shows the errors on the fields itself.

<!-- slide 30 -->

### A field has required. Somebody removes the attribute in the developer tools and sends the form empty. What stops it?

- A. The browser remembers the attribute
- B. Nothing in the browser, only a check on the server
- C. The submit event refuses to fire
- D. Your CSS

**Answer:** B. Nothing in the browser, only a check on the server

Everything in the browser belongs to the visitor, and the developer tools can change all of it. Client-side validation is for comfort. Only the server can make sure the data is right.

<!-- slide 31 -->

## 5. Validation in JavaScript

<!-- slide 32 -->

### The simplest check

```html
<form id="signup">
  <input id="name" name="name" placeholder="Your name">
  <button>Send</button>
</form>

<script>
  const nameInput = document.querySelector('#name');

  document.querySelector('#signup').addEventListener('submit', function (event) {
    event.preventDefault();

    if (nameInput.value.trim() === '') {
      console.log('Name is required');
    } else {
      console.log('Hello ' + nameInput.value.trim());
    }
  });
</script>
```

<!-- slide 33 -->

### Show it on the field

```html
<style>
  .error { border: 2px solid red; background: #ffe5e5; }
</style>

<form id="signup">
  <input id="name" name="name" placeholder="Your name">
  <button>Send</button>
</form>

<script>
  const nameInput = document.querySelector('#name');

  document.querySelector('#signup').addEventListener('submit', function (event) {
    event.preventDefault();

    if (nameInput.value.trim() === '') {
      nameInput.classList.add('error');
    } else {
      nameInput.classList.remove('error');
    }
  });
</script>
```

<!-- slide 34 -->

### Send it when it is right

```html
<style>
  .error { border: 2px solid red; background: #ffe5e5; }
</style>

<form id="signup">
  <input id="name" name="name" placeholder="Your name">
  <button>Send</button>
</form>

<script>
  console.log('Page loaded', location.search);

  const form = document.querySelector('#signup');
  const nameInput = document.querySelector('#name');

  form.addEventListener('submit', function (event) {
    event.preventDefault();

    if (nameInput.value.trim() === '') {
      nameInput.classList.add('error');
    } else {
      nameInput.classList.remove('error');
      form.submit();
    }
  });
</script>
```

<!-- slide 35 -->

### More than one field

```js
event.preventDefault();
let success = true;

if (nameInput.value.trim() === '') {
  nameInput.classList.add('error');
  success = false;
} else {
  nameInput.classList.remove('error');
}

if (success) {
  form.submit();
}
```

1. `success` starts on true. Innocent until proven guilty.
2. Every check that fails sets it to false. The same block again for every other field.
3. Only when nothing failed, the form is sent.

<!-- slide 36 -->

### Three fields

```html
<style>
  .error { border: 2px solid red; background: #ffe5e5; }
</style>

<form id="signup" novalidate>
  <label for="name">Name</label>
  <input id="name" name="name">
  <br>
  <label for="email">Email</label>
  <input id="email" name="email" type="email">
  <br>
  <label for="password">Password</label>
  <input id="password" name="password" type="password">
  <br>
  <button>Sign up</button>
</form>

<script>
  const form = document.querySelector('#signup');
  const nameInput = document.querySelector('#name');
  const email = document.querySelector('#email');
  const password = document.querySelector('#password');

  form.addEventListener('submit', function (event) {
    event.preventDefault();
    let success = true;

    if (nameInput.value.trim() === '') {
      nameInput.classList.add('error');
      success = false;
    } else {
      nameInput.classList.remove('error');
    }

    if (!email.value.includes('@')) {
      email.classList.add('error');
      success = false;
    } else {
      email.classList.remove('error');
    }

    if (password.value === '') {
      password.classList.add('error');
      success = false;
    } else {
      password.classList.remove('error');
    }

    if (success) {
      console.log('All good, sending');
      form.submit();
    }
  });
</script>
```

<!-- slide 37 -->

**Copy, paste, repeat?**

Three fields, three times the same block. A contact form with ten fields is a hundred lines of copy and paste, and every new field means more JavaScript.

<!-- slide 38 -->

## 6. validator--required

<!-- slide 39 -->

### Mark the field, not the code

```html
<label for="firstname">First name</label>
<input id="firstname" class="validator--required">

<label for="email">Email</label>
<input id="email" type="email" class="validator--required">

<label for="message">Message</label>
<textarea id="message" class="validator--required"></textarea>

<label for="phone">Phone</label>
<input id="phone">
```

- Every field that has to be filled in gets `validator--required`.
- The phone number does not, so it stays optional.
- A new required field? Add the class. No extra JavaScript.

<!-- slide 40 -->

### One function for every field

```js
function validateField(field) {
  if (field.value.trim() === '') {
    field.classList.add('error');
    return false;
  }
  if (field.type === 'email' && !field.value.includes('@')) {
    field.classList.add('error');
    return false;
  }
  field.classList.remove('error');
  return true;
}
```

1. The field comes in as a parameter. Which one does not matter.
2. Empty? Error class on, and `false` back.
3. An email field without an @? The same.
4. Made it this far: no error, and `true` back.

<!-- slide 41 -->

### Loop over the class

```js
const form = document.querySelector('#contact');

form.addEventListener('submit', function (event) {
  event.preventDefault();
  let success = true;

  document.querySelectorAll('.validator--required').forEach(function (field) {
    if (!validateField(field)) {
      success = false;
    }
  });

  if (success) {
    form.submit();
  }
});
```

1. Stop the submit first, as always.
2. Every field with the class goes through the same function.
3. Only when every field was right, the form is sent.

<!-- slide 42 -->

### All together

```html
<style>
  .error { border: 2px solid red; background: #ffe5e5; }
</style>

<form id="contact" novalidate>
  <label for="firstname">First name</label>
  <input id="firstname" name="firstname" class="validator--required">
  <br>
  <label for="lastname">Last name</label>
  <input id="lastname" name="lastname" class="validator--required">
  <br>
  <label for="email">Email</label>
  <input id="email" name="email" type="email" class="validator--required">
  <br>
  <label for="phone">Phone</label>
  <input id="phone" name="phone">
  <br>
  <label for="message">Message</label>
  <textarea id="message" name="message" class="validator--required"></textarea>
  <br>
  <button>Send</button>
</form>

<script>
  const form = document.querySelector('#contact');

  function validateField(field) {
    if (field.value.trim() === '') {
      field.classList.add('error');
      return false;
    }
    if (field.type === 'email' && !field.value.includes('@')) {
      field.classList.add('error');
      return false;
    }
    field.classList.remove('error');
    return true;
  }

  form.addEventListener('submit', function (event) {
    event.preventDefault();
    let success = true;

    document.querySelectorAll('.validator--required').forEach(function (field) {
      if (!validateField(field)) {
        success = false;
      }
    });

    if (success) {
      console.log('All good, sending');
      form.submit();
    }
  });
</script>
```

<!-- slide 43 -->

### The phone field has no validator--required. Somebody leaves it empty and fills in the rest. What happens on submit?

- A. The phone field turns red
- B. The form is sent, with an empty phone number
- C. Nothing is sent
- D. An error in the console

**Answer:** B. The form is sent, with an empty phone number

querySelectorAll only finds the fields with the class, so validateField never sees the phone field. That is exactly how you make a field optional: leave the class out.

<!-- slide 44 -->

### Dynamic: while you type

- Now the red border only changes on a submit. You fix the field, and it stays red until you send again.
- Better: every required field also gets an `input` listener, that calls `validateField` again.
- But not from the first key. Nobody types a whole email address in one go.
- **Check late, forgive early:** a field that already has an error checks itself while you type, so the red goes away as soon as it is right.

<!-- slide 45 -->

### Forgive early

```js
document.querySelectorAll('.validator--required').forEach(function (field) {
  field.addEventListener('input', function () {
    if (field.classList.contains('error')) {
      validateField(field);
    }
  });
});
```

1. Every required field, once, when the page loads.
2. Listen to every key in that field.
3. Only a field that is already red checks itself again.

<!-- slide 46 -->

### Try both

```html
<style>
  .error { border: 2px solid red; background: #ffe5e5; }
</style>

<form id="contact" novalidate>
  <label for="name">Name</label>
  <input id="name" name="name" class="validator--required">
  <br>
  <label for="email">Email</label>
  <input id="email" name="email" type="email" class="validator--required">
  <br>
  <button>Send</button>
</form>

<script>
  const form = document.querySelector('#contact');
  const fields = document.querySelectorAll('.validator--required');

  function validateField(field) {
    if (field.value.trim() === '') {
      field.classList.add('error');
      return false;
    }
    if (field.type === 'email' && !field.value.includes('@')) {
      field.classList.add('error');
      return false;
    }
    field.classList.remove('error');
    return true;
  }

  fields.forEach(function (field) {
    field.addEventListener('input', function () {
      if (field.classList.contains('error')) {
        validateField(field);
      }
    });
  });

  form.addEventListener('submit', function (event) {
    event.preventDefault();
    let success = true;

    fields.forEach(function (field) {
      if (!validateField(field)) {
        success = false;
      }
    });

    if (success) {
      console.log('All good, sending');
      form.submit();
    }
  });
</script>
```

*only when red*

```html
<style>
  .error { border: 2px solid red; background: #ffe5e5; }
</style>

<form id="contact" novalidate>
  <label for="name">Name</label>
  <input id="name" name="name" class="validator--required">
  <br>
  <label for="email">Email</label>
  <input id="email" name="email" type="email" class="validator--required">
  <br>
  <button>Send</button>
</form>

<script>
  const form = document.querySelector('#contact');
  const fields = document.querySelectorAll('.validator--required');

  function validateField(field) {
    if (field.value.trim() === '') {
      field.classList.add('error');
      return false;
    }
    if (field.type === 'email' && !field.value.includes('@')) {
      field.classList.add('error');
      return false;
    }
    field.classList.remove('error');
    return true;
  }

  fields.forEach(function (field) {
    field.addEventListener('input', function () {
      if (field.classList.contains('error')) {
        validateField(field);
      }
    });
  });

  form.addEventListener('submit', function (event) {
    event.preventDefault();
    let success = true;

    fields.forEach(function (field) {
      if (!validateField(field)) {
        success = false;
      }
    });

    if (success) {
      console.log('All good, sending');
      form.submit();
    }
  });
</script>
```

*every key*

```html
<style>
  .error { border: 2px solid red; background: #ffe5e5; }
</style>

<form id="contact" novalidate>
  <label for="name">Name</label>
  <input id="name" name="name" class="validator--required">
  <br>
  <label for="email">Email</label>
  <input id="email" name="email" type="email" class="validator--required">
  <br>
  <button>Send</button>
</form>

<script>
  const form = document.querySelector('#contact');
  const fields = document.querySelectorAll('.validator--required');

  function validateField(field) {
    if (field.value.trim() === '') {
      field.classList.add('error');
      return false;
    }
    if (field.type === 'email' && !field.value.includes('@')) {
      field.classList.add('error');
      return false;
    }
    field.classList.remove('error');
    return true;
  }

  fields.forEach(function (field) {
    field.addEventListener('input', function () {
      validateField(field);
    });
  });

  form.addEventListener('submit', function (event) {
    event.preventDefault();
    let success = true;

    fields.forEach(function (field) {
      if (!validateField(field)) {
        success = false;
      }
    });

    if (success) {
      console.log('All good, sending');
      form.submit();
    }
  });
</script>
```

<!-- slide 47 -->

### Only part of the form

```js
function validateStep(step) {
  let success = true;
  step.querySelectorAll('.validator--required').forEach(function (field) {
    if (!validateField(field)) {
      success = false;
    }
  });
  return success;
}

nextButton.addEventListener('click', function () {
  if (validateStep(step1)) {
    step1.classList.add('hidden');
    step2.classList.remove('hidden');
  }
});
```

1. `step.querySelectorAll` only looks inside that step.
2. Next only shows step 2 when step 1 is right.

<!-- slide 48 -->

### Why does the input listener only call validateField when the field already has the error class?

- A. Otherwise an email field turns red on the first letter you type
- B. Because validateField does not work during typing
- C. classList.contains is faster than validateField
- D. The input event only fires on fields with an error

**Answer:** A. Otherwise an email field turns red on the first letter you type

Checked on every key, an email field is wrong until the @ is typed, so it turns red while the visitor is still busy. Only checking fields that are already red means the error appears after a submit, and disappears the moment it is fixed.

<!-- slide 49 -->

## 7. Exercises

<!-- slide 50 -->

> Help will always be given at Hoboken to those who ask for it.
>
> Almost Dumbledore

<!-- slide 51 -->

### How it works

- One folder per exercise, with an `index.html`, a `style.css` and a `script.js` with `defer`.
- Every field gets a label, every field that is sent gets a name.
- **No alert.** Errors go on the field, results into the page.
- Opened with Live Server, with the console open.
- Stuck for more than ten minutes? Ask a classmate, ask on Discord, then look at the solution.

<!-- slide 52 -->

### Task: Calculator

1. A form with two number fields, a select with +, −, × and ÷, and a button "Calculate".
2. On submit: preventDefault, read the three values, calculate, and show the result in the page.
3. An empty field? Put `required` on both and let the browser stop it.
4. Extra: draw as many blocks as the result under it.

> [!TIP]
> **Calculator**
>
> *index.html*
>
> *index.html*
>
> ```html
> <form id="calculator">
>   <input type="number" name="num1" placeholder="Number 1" required>
>   <select name="operator">
>     <option value="add">+</option>
>     <option value="subtract">−</option>
>     <option value="multiply">×</option>
>     <option value="divide">÷</option>
>   </select>
>   <input type="number" name="num2" placeholder="Number 2" required>
>   <button>Calculate</button>
> </form>
>
> <h2>Result: <span id="result"></span></h2>
> <div id="blocks"></div>
> ```
>
> *script.js*
>
> *script.js*
>
> ```js
> const calculator = document.querySelector('#calculator');
>
> calculator.addEventListener('submit', function (event) {
>   event.preventDefault();
>
>   const num1 = Number(calculator.num1.value);
>   const num2 = Number(calculator.num2.value);
>   let result;
>
>   switch (calculator.operator.value) {
>     case 'add': result = num1 + num2; break;
>     case 'subtract': result = num1 - num2; break;
>     case 'multiply': result = num1 * num2; break;
>     case 'divide': result = num1 / num2; break;
>   }
>
>   document.querySelector('#result').textContent = result;
>
>   const blocks = document.querySelector('#blocks');
>   blocks.innerHTML = '';
>   for (let i = 0; i < result; i++) {
>     blocks.innerHTML += '<div class="block"></div>';
>   }
> });
> ```

<!-- slide 53 -->

### Task: Fuel cost

1. A number field for the kilometres, and a select with the fuel: gas 0.13, diesel 0.15, electric 0.08 euro per km.
2. A button with `type="button"`. A click shows the price of the trip in the page, with two decimals.
3. Extra: drop the button. The price updates while you type, and when you pick another fuel.

> [!TIP]
> **Fuel cost**
>
> *index.html*
>
> *index.html*
>
> ```html
> <form>
>   <label for="kilometers">Kilometres</label>
>   <input type="number" id="kilometers" name="kilometers">
>
>   <label for="fuel">Fuel</label>
>   <select id="fuel" name="fuel">
>     <option value="0.13">Gas</option>
>     <option value="0.15">Diesel</option>
>     <option value="0.08">Electric</option>
>   </select>
>
>   <button type="button" id="calculate">Calculate price</button>
> </form>
> <p id="price"></p>
> ```
>
> *script.js*
>
> *script.js*
>
> ```js
> const kilometers = document.querySelector('#kilometers');
> const fuel = document.querySelector('#fuel');
> const price = document.querySelector('#price');
>
> function calculate() {
>   const total = Number(kilometers.value) * Number(fuel.value);
>   price.textContent = '€ ' + total.toFixed(2);
> }
>
> document.querySelector('#calculate').addEventListener('click', calculate);
>
> // Extra: without the button
> kilometers.addEventListener('input', calculate);
> fuel.addEventListener('change', calculate);
> ```

<!-- slide 54 -->

### Task: Helpdesk

1. A form with a category (general, technical, finance), an email address and a description. novalidate on the form.
2. On submit: an email without an @ gets the error class, and the form is not sent.
3. A description with the word "dummy" in it sends the visitor to chatgpt.com instead.
4. Everything fine: `form.submit()`, to a thankyou.html of your own.

> [!TIP]
> **Helpdesk**
>
> *index.html*
>
> *index.html*
>
> ```html
> <form id="helpdesk" action="thankyou.html" novalidate>
>   <label for="category">Category</label>
>   <select id="category" name="category">
>     <option value="general">General</option>
>     <option value="technical">Technical</option>
>     <option value="finance">Finance</option>
>   </select>
>
>   <label for="email">Email</label>
>   <input id="email" name="email" type="email">
>
>   <label for="description">Description</label>
>   <textarea id="description" name="description"></textarea>
>
>   <button>Send</button>
> </form>
> ```
>
> *script.js*
>
> return stops the function: nothing after it runs, so the form is not sent.
>
> *script.js*
>
> ```js
> const form = document.querySelector('#helpdesk');
> const email = document.querySelector('#email');
> const description = document.querySelector('#description');
>
> form.addEventListener('submit', function (event) {
>   event.preventDefault();
>
>   if (!email.value.includes('@')) {
>     email.classList.add('error');
>     return;
>   }
>   email.classList.remove('error');
>
>   if (description.value.includes('dummy')) {
>     location.href = 'https://chatgpt.com';
>     return;
>   }
>
>   form.submit();
> });
> ```

<!-- slide 55 -->

### Task: Contact form

1. First name, last name, email and message, all with the class `validator--required`. A phone number without it.
2. `novalidate` and `action="thankyou.html"` on the form, and a thankyou.html next to it.
3. On submit: every empty field gets the error class, an email without @ too. Only when everything is right: `form.submit()`.
4. Dynamic: a field with an error checks itself again while you type.
5. Extra: a paragraph under every field with a sentence that says what is wrong.

> [!TIP]
> **Contact form**
>
> *index.html*
>
> *index.html*
>
> ```html
> <form id="contact" action="thankyou.html" novalidate>
>   <label for="firstname">First name</label>
>   <input id="firstname" name="firstname" class="validator--required">
>
>   <label for="lastname">Last name</label>
>   <input id="lastname" name="lastname" class="validator--required">
>
>   <label for="email">Email</label>
>   <input id="email" name="email" type="email" class="validator--required">
>
>   <label for="phone">Phone</label>
>   <input id="phone" name="phone" type="tel">
>
>   <label for="message">Message</label>
>   <textarea id="message" name="message" class="validator--required"></textarea>
>
>   <button>Send</button>
> </form>
> ```
>
> *script.js*
>
> *script.js*
>
> ```js
> const form = document.querySelector('#contact');
> const fields = document.querySelectorAll('.validator--required');
>
> function validateField(field) {
>   if (field.value.trim() === '') {
>     field.classList.add('error');
>     return false;
>   }
>   if (field.type === 'email' && !field.value.includes('@')) {
>     field.classList.add('error');
>     return false;
>   }
>   field.classList.remove('error');
>   return true;
> }
>
> fields.forEach(function (field) {
>   field.addEventListener('input', function () {
>     if (field.classList.contains('error')) {
>       validateField(field);
>     }
>   });
> });
>
> form.addEventListener('submit', function (event) {
>   event.preventDefault();
>   let success = true;
>
>   fields.forEach(function (field) {
>     if (!validateField(field)) {
>       success = false;
>     }
>   });
>
>   if (success) {
>     form.submit();
>   }
> });
> ```
>
> *Extra*
>
> An empty paragraph right after every field, filled in or emptied by validateField. nextElementSibling is the element right after the field.
>
> *index.html*
>
> ```html
> <input id="email" name="email" type="email" class="validator--required">
> <p class="message"></p>
> ```
>
> *script.js*
>
> ```js
> function validateField(field) {
>   const message = field.nextElementSibling;
>
>   if (field.value.trim() === '') {
>     field.classList.add('error');
>     message.textContent = 'This one is required';
>     return false;
>   }
>   if (field.type === 'email' && !field.value.includes('@')) {
>     field.classList.add('error');
>     message.textContent = 'That is no email address';
>     return false;
>   }
>   field.classList.remove('error');
>   message.textContent = '';
>   return true;
> }
> ```

<!-- slide 56 -->

### Task: Two steps

1. Split the contact form in two divs: step 1 with the names and the email, step 2 with the message.
2. Step 2 starts hidden. A button "Next step" with `type="button"` checks only the fields of step 1, and shows step 2 when they are right.
3. A button "Previous step" goes back, without checking anything.
4. Submit checks step 2 and sends the form.

> [!TIP]
> **Two steps**
>
> *index.html*
>
> *index.html*
>
> ```html
> <form id="contact" action="thankyou.html" novalidate>
>   <div id="step1">
>     <!-- first name, last name, email -->
>     <button type="button" id="next">Next step</button>
>   </div>
>
>   <div id="step2" class="hidden">
>     <!-- message -->
>     <button type="button" id="previous">Previous step</button>
>     <button>Send</button>
>   </div>
> </form>
> ```
>
> *script.js*
>
> validateField and the input listeners stay the same as in the contact form. In style.css: .hidden { display: none; }
>
> *script.js*
>
> ```js
> const form = document.querySelector('#contact');
> const step1 = document.querySelector('#step1');
> const step2 = document.querySelector('#step2');
>
> function validateStep(step) {
>   let success = true;
>   step.querySelectorAll('.validator--required').forEach(function (field) {
>     if (!validateField(field)) {
>       success = false;
>     }
>   });
>   return success;
> }
>
> document.querySelector('#next').addEventListener('click', function () {
>   if (validateStep(step1)) {
>     step1.classList.add('hidden');
>     step2.classList.remove('hidden');
>   }
> });
>
> document.querySelector('#previous').addEventListener('click', function () {
>   step2.classList.add('hidden');
>   step1.classList.remove('hidden');
> });
>
> form.addEventListener('submit', function (event) {
>   event.preventDefault();
>   if (validateStep(step2)) {
>     form.submit();
>   }
> });
> ```

<!-- slide 57 -->

### Next up

- **23/11** Forms: Today
- **30/11** JavaScript libraries
- **07/12** jQuery
- **14/12** JavaScript & AI

## Glossary

- **Form**: The <form> element around the fields that belong together. It knows its fields, and it fires one submit event, whether the visitor clicks the button or presses Enter. (slide 3)
- **Label**: The text that says what goes in a field, linked to it with for and id. A click on the label puts the cursor in the field. A placeholder is no label. (slide 8)
- **name attribute**: The key under which a field is sent with the form. A field without a name is left out. (slide 9)
- **value**: What is in a field right now, as a string. Also for type="number": Number() before you calculate. (slide 13)
- **submit event**: Fires on the form when it is sent: by a click on a submit button or by Enter in a field. Listen to it on the form, not to the click on the button. (slide 20)
- **preventDefault**: A method of the event object that cancels what the browser would do next. On a submit: the form is not sent and the page is not reloaded, so your script can check it first. (slide 22)
- **form.submit()**: Sends the form from your script, after a preventDefault. It does not fire the submit event again, so your check does not run twice. (slide 34)
- **Client-side validation**: Checks in the browser, with HTML attributes or JavaScript, before a form is sent. Faster feedback for the visitor, no protection at all: anybody can switch it off. (slide 26)
- **Server-side validation**: The same checks again on the server that receives the data. The only ones you can trust, because the visitor cannot change them. (slide 26)
- **novalidate**: An attribute on the form that switches off the checks and the bubbles of the browser, so your JavaScript can do the checking and show the errors its own way. (slide 29)
- **validator--required**: A class you put on every field that has to be filled in. Your script loops over that class, so a new field is checked without a line of extra JavaScript. (slide 39)

## Links and sources

### In the deck

- [<form>](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/form) (slide 6)
- [<label>](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/label) (slide 6)
- [<input>](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input) (slide 6)
- [<textarea>](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/textarea) (slide 6)
- [<select>](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/select) (slide 6)
- [<button>](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/button) (slide 6)
- [kdgmt.be/discord](https://kdgmt.be/discord) (slide 58)

### Sources

- [Web forms, working with user data](https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Forms): The MDN guide on forms, from the first field to validation
- [Client-side form validation](https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Forms/Form_validation)
- [HTMLFormElement: submit() method](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit)
