The DOM & Form Submission
Learning Competencies
By the end of this section, you should be familiar with and able to:
- Explain form submission in relation to the DOM
Time Box
Activity | Time |
---|---|
Form Submission | 30 minutes |
Form submission
OK, one last thing. What if we want to capture a form submission and handle it on the front end (aka in the browser) instead of submitting it to the server?
Let's add a simple form to our page:
<!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></body></html>
And below is the code we're going to use. It's pretty similar to the previous exercise. But what is that preventDefault()
bit?
Well, the usual default action when we submit a form is to make a POST request to the server and reload the page with the response (you'll learn about how that works during Bootcamp). But we want to prevent page reload so that we can display some stuff onscreen, therefore we want to prevent the default action. Conveniently, the e
event object comes with a method called preventDefault()
that does precisely that, so it's easy!
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)
Try it out in your test HTML form page (open your console, enter the code discussed above, then write some text in the input box and click submit):

Figure 16: You should see something like this.
Break time
Phew, we made it! Head on over to the next section for a look at some resources you can use to write a blog post about the DOM.