Emmanuel Akinfulubi

JavaScriptEvents

Prevent form submission and read values in JavaScript

Beginner · 4 min read

When you press Submit on a plain HTML form, the browser packs up the fields, sends them to a server and loads a new page. Most modern sites don't want that. They want to read the values with JavaScript, check them, and send them in the background while the page stays put. The first step is always the same: stop the browser's own submission.

In this tutorial you will stop a booking form from submitting, read every named field into an object, and learn why the values are always text, even from a number field. You should have used addEventListener and know what an object is.

Default actions

Many events come with something the browser does by itself afterwards. A link's click follows the link. A form's submit sends the form and loads a page. These are called default actions.

event.preventDefault() inside your listener cancels the default action. Your code still runs, the browser just skips its own part.

Listen to the form, not the button

There's more than one way to submit a form. Clicking the Submit button is one. Pressing Enter inside a text field is another, and no click happens at all. Every route fires a submit event on the form, so that's the event to listen for. A click listener on the button would miss the Enter key.

Here is the page:

index.html

<form id="form">
  <input name="from" value="Ojota">
  <input name="to" value="Abuja">
  <input name="seats" type="number" value="2">
  <button type="submit">Submit</button>
</form>

Here is the exercise. Try it on your own first, or read on and we will build it together.

12 Stop a form submitting and read the values

easy

Prevent a form's default submission and record the input values instead.

Stuck? Three hints, smallest first
  1. 1. event.preventDefault() in the submit handler stops the navigation.
  2. 2. Listen for submit on the form, not click on the button. Enter in a field submits too.
  3. 3. new FormData(form) reads every named field at once.

Step 1: stop the submission

Step 1

const form = document.getElementById('form');
form.addEventListener('submit', (event) => {
  event.preventDefault();
});
const event = new Event('submit', { bubbles: true, cancelable: true });
const result = form.dispatchEvent(event);
console.log(event.defaultPrevented, result); // true false

We fake a submit with dispatchEvent. Afterwards, event.defaultPrevented is true, which confirms the cancel worked. dispatchEvent itself returns false when a listener cancelled the default, and true otherwise.

Put preventDefault() first in the handler. If a later line throws an error, the cancel has already happened, and the page won't navigate away halfway through.

Step 2: read the fields

form.elements is a list of all the form's controls: its inputs, selects, text areas and buttons. Each has a name and a value.

Step 2

const form = document.getElementById('form');
const logged = [];
form.addEventListener('submit', (event) => {
  event.preventDefault();
  const data = {};
  for (const field of event.target.elements) {
    if (!field.name) continue;
    data[field.name] = field.value;
  }
  logged.push(data);
});
form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
console.log(logged[0]); // { from: 'Ojota', to: 'Abuja', seats: '2' }

event.target is the form that was submitted. The loop copies each field into data, using its name as the key. The Submit button has no name, so continue skips it and it doesn't end up as an empty key.

Step 3: values are strings

Look closely at seats: '2'. It's in quotes. An input's value is always a string, even when the input has type="number".

Step 3

const seats = logged[0].seats;
console.log(typeof seats); // string
console.log(seats + 1);    // 21
console.log(Number(seats) + 1); // 3

With a string, + joins text, so '2' + 1 is '21'. Convert with Number() as soon as the value leaves the form, before you do any arithmetic with it.

Step 4: events you send yourself

A real submit can always be cancelled. An event you create in code can't, unless you say so:

Step 4

const plain = new Event('submit', { bubbles: true });
plain.preventDefault();
console.log(plain.defaultPrevented); // false

Events made with new Event(...) are not cancelable by default, so preventDefault() does nothing to them. If you ever fake an event in a test and preventDefault seems broken, check for a missing cancelable: true first.

Step 5: a shortcut for reading fields

In a browser, FormData reads every named field at once:

JavaScript

const data = Object.fromEntries(new FormData(form));

new FormData(form) collects the name and value of each field, and Object.fromEntries turns that into a plain object like the one from Step 2. The values are still strings. The live demo uses this line; the full solution uses the loop from Step 2, which runs anywhere.

The full solution

The panel builds the form, submits it from code, and logs the values. Its checks confirm the default was prevented, every named field was captured and the unnamed button was skipped, the number field gives a string, dispatchEvent returns false when the default is prevented, preventDefault does nothing on a non-cancelable event, and changing a field changes what's logged. Press Run, then submit the live demo, including with Enter inside a field.

Live, in a real browser. Click it. Sandboxed to allow-scripts only, so it cannot reach this page.

The answer

const form = el('form', { id: 'form' }, [
  el('input', { name: 'from', value: 'Ojota' }),
  el('input', { name: 'to', value: 'Abuja' }),
  el('input', { name: 'seats', type: 'number', value: '2' }),
  el('button', { type: 'submit' }, 'Submit'),
]);
document.body.appendChild(form);

const logged = [];

// submit on the FORM, not click on the button: pressing Enter in a text field
// submits as well, and a click listener would miss it entirely.
form.addEventListener('submit', (event) => {
  event.preventDefault();
  const data = {};
  for (const field of event.target.elements) {
    if (!field.name) continue;                 // the submit button has no name
    data[field.name] = field.value;            // always a string
  }
  logged.push(data);
});

const event = new Event('submit', { bubbles: true, cancelable: true });
form.dispatchEvent(event);

console.log('default prevented:', event.defaultPrevented);
console.log('values logged    :', logged[0]);
console.log('seats is a', typeof logged[0].seats, 'not a number');

// preventDefault only works on a cancelable event.
const notCancelable = new Event('submit', { bubbles: true, cancelable: false });
notCancelable.preventDefault();
console.log('preventDefault on a non-cancelable event:', notCancelable.defaultPrevented);

Output


      
12 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 12 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

12 checks

test('the default was prevented', event.defaultPrevented, true);
test('one submission was logged', logged.length, 1);
test('every named field is captured', Object.keys(logged[0]), ['from', 'to', 'seats']);
test('the values are right', logged[0].from, 'Ojota');
test('the unnamed submit button is skipped', Object.keys(logged[0]).includes(''), false);
test('a number input still gives a string', typeof logged[0].seats, 'string');
test('so it needs converting before arithmetic', Number(logged[0].seats) + 1, 3);
test('while the string would concatenate', logged[0].seats + 1, '21');
test('dispatchEvent returns false when the default was prevented', form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })), false);
test('a second submission logs again', logged.length, 2);
test('preventDefault does nothing on a non-cancelable event', notCancelable.defaultPrevented, false);
test('changing a value changes what is logged', (() => { form.elements[0].value = 'Berger'; fire(form, 'submit'); return logged.at(-1).from; })(), 'Berger');

Two habits. Listen for submit on the form rather than click on the button, because Enter inside a text field submits the form without any click happening — a click listener silently misses that path. And call preventDefault() first, before any work that could throw, so an error later cannot leave the page navigating away.

The typeof assertions are the detail worth carrying: input.value is a string even for type="number", so seats + 1 gives "21" rather than 3. Convert at the boundary, as soon as the value leaves the DOM.

preventDefault() also only does anything on a cancelable event, which the last assertion shows. Events you dispatch yourself default to cancelable: false, so a hand-made event that ignores preventDefault is usually a missing option rather than a broken handler.

Common mistakes

  • Listening for click on the button. Pressing Enter in a field submits without a click. Listen for submit on the form.
  • Calling preventDefault() at the end. If anything before it throws, the page navigates away. Call it first.
  • Doing arithmetic on value. It's a string, so + joins text. Convert with Number() first.

Try it yourself

  1. Show the logged object on the page with JSON.stringify(data, null, 2) inside a pre element.
  2. Convert seats to a number and refuse the booking if it's less than 1 or not a whole number.
  3. After a successful submit, call form.reset() and check which values the fields go back to.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.