The DOM & Form Submission

The Big Idea

By default, submitting a form sends a request to a server and reloads the page. JavaScript lets you intercept that submission, stop the reload, and handle the data yourself — right in the browser.


Your Roadmap

SectionTimeRequired?
Set up the form page5 min⚑ Required
Intercept the form submission15 min⚑ Required

Set up the form page

Update dom-lesson.html with a simple form:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
</head>
<body>
<div id="app">
<header>
<h1>My form submission test page</h1>
</header>
<main>
<form id="catch-it">
<input id="some-text" />
<input type="submit" />
</form>
<p id="outputter"></p>
</main>
</div>
</body>
</html>

Save the file and refresh Chrome.


Intercept the form submission

Listen for the submit event on the form — it works just like a click listener, but fires when the form is submitted.

let form = document.querySelector('#catch-it')
let input = document.querySelector('#some-text')
let output = document.querySelector('#outputter')
function updater(e) {
e.preventDefault()
output.innerHTML = 'Submitting form with "' + input.value + '"'
}
form.addEventListener('submit', updater)

Type something in the input and click Submit. You should see the value appear in the paragraph below — without the page reloading.

An HTML form with a paragraph below showing the submitted value

Figure 16: The submitted value is displayed on the page.

What does e.preventDefault() do?

When a form is submitted, the browser's default behaviour is to send the form data to a server and reload the page. During Bootcamp you'll learn how that server-side flow works.

For now, we want to stay on the page and handle the data ourselves. Calling e.preventDefault() stops the browser from doing its default thing — so no reload happens and we can display the result ourselves.

e is the event object (same as event in earlier examples — the name is just shorter). Every event object has a preventDefault() method available on it.


How to know you've nailed it

LevelYou can...
🪨Intro ClimbAttach a submit listener to a form and stop the page from reloading⚑ Required
🧗Core AscentRead the input value on submission and display it elsewhere on the page⚑ Required
🏔️SummitExplain what preventDefault does and why it's needed for front-end form handling◎ Optional

The Big Idea (revisited)

Listening for a submit event works the same way as listening for a click. The key difference is e.preventDefault() — without it, the browser reloads the page before your code can do anything.


Extra Resources

These are optional. Use them if you want to go deeper.