JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 13: Forms and ValidationLesson 62 of 150About 45 minutes

Lesson 62: Input events and form submission

01Opening question

Should a search box react to every key press, or only when you press Enter? And what stops a form from reloading the page?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

Listen for submit on the form, not click on the button, and call preventDefault so the browser does not reload the page.

const form = document.querySelector("#search");
form.addEventListener("submit", (event) => {
  event.preventDefault();
  console.log("Searching for", form.elements.q.value);
});
form.elements.q.value = "lamps";
form.requestSubmit();

03Objective and prerequisites

Learning objective: Choose between input, change and submit events, handle form submission with preventDefault, and reset forms safely.

You need: Lesson 61: Reading form values, Lesson 57: Event objects

Skills practised: Forms, Form events and submission.

04Explanation

The input event fires on every change to a field's value: each key typed, each paste. Use it for live feedback such as character counts or instant search.

The change event fires when the person commits a change: leaving a text box, picking a select option, ticking a checkbox.

The submit event fires on the <form> when the person presses Enter in a field or clicks the submit button. Listen on the form so both ways are handled.

Without event.preventDefault(), submitting a form sends it and loads a new page. In JavaScript apps you cancel that and handle the data yourself.

05Definitions

input event
Fires every time a field's value changes.
change event
Fires when a change is committed, such as leaving a field or choosing an option.
submit event
Fires on a form when it is submitted with Enter or a submit button.
requestSubmit
A form method that submits the form the way a user would, including validation and the submit event.
form.reset
A method that puts every control back to its initial value.

Open the full glossary

06Visual learning object

Form data inspector. Type, change and submit a live form and watch the timeline of input, change and submit events next to the form data.

Loading the interactive object…

Open the full Form data inspector page with its guided experiment.

07Examples

ex-062-01Live character count Browser page (sandboxed preview)

input fires on every edit, so the counter stays current.

const bio = document.querySelector("#bio");
const left = document.querySelector("#left");
bio.addEventListener("input", () => {
  left.textContent = (40 - bio.value.length) + " left";
});
bio.value = "Hello";
bio.dispatchEvent(new Event("input"));
console.log(left.textContent);
Sample input
None
Expected output
35 left
Common mistake
Using change, which only updates after the person leaves the field.
Try this
Turn the text red when fewer than 10 characters are left.
Source
examples/ex-062-01-char-count.js

ex-062-02input versus change Browser page (sandboxed preview)

Typing fires input many times; change fires once when committed.

const city = document.querySelector("#city");
const log = [];
city.addEventListener("input", () => log.push("input:" + city.value));
city.addEventListener("change", () => log.push("change:" + city.value));
for (const text of ["P", "Pa", "Par"]) {
  city.value = text;
  city.dispatchEvent(new Event("input"));
}
city.dispatchEvent(new Event("change"));
console.log(log.join(" "));
Sample input
None
Expected output
input:P input:Pa input:Par change:Par
Common mistake
Running an expensive search on input without debouncing.
Try this
Add a keydown listener and see where it fits.
Source
examples/ex-062-02-input-vs-change.js

ex-062-03Handling submit Browser page (sandboxed preview)

One submit listener handles Enter and the button; preventDefault keeps the page.

const form = document.querySelector("#todo");
form.addEventListener("submit", (event) => {
  event.preventDefault();
  const li = document.createElement("li");
  li.textContent = form.elements.task.value;
  document.querySelector("#list").append(li);
  form.reset();
});
form.elements.task.value = "Water plants";
form.requestSubmit();
console.log(document.querySelector("#list").textContent, JSON.stringify(form.elements.task.value));
Sample input
None
Expected output
Water plants ""

An empty field and a list with Water plants

Common mistake
Listening for click on the button and missing submissions made with Enter.
Try this
Ignore empty tasks.
Source
examples/ex-062-03-submit.js

ex-062-04Which button submitted? Browser page (sandboxed preview)

event.submitter tells two submit buttons apart.

const form = document.querySelector("#post");
form.addEventListener("submit", (event) => {
  event.preventDefault();
  console.log(event.submitter.value, "->", form.elements.title.value);
});
const [draft, publish] = form.querySelectorAll("button");
form.requestSubmit(publish);
form.requestSubmit(draft);
Sample input
None
Expected output
publish -> Spring sale draft -> Spring sale
Common mistake
Adding click listeners to both buttons and duplicating the submit logic.
Try this
Disable both buttons while saving.
Source
examples/ex-062-04-submitter.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

The form reloads the page

Cancel the default submission.

let signedIn = null;
const form = document.querySelector("#login");
form.addEventListener("submit", () => {
  signedIn = form.elements.user.value;
});
form.requestSubmit();
console.log("Signed in as", signedIn);

Live filter

React to every keystroke with input.

const filter = document.querySelector("#filter");
const items = [...document.querySelectorAll("#fruits li")];
// TODO: on input, hide every li whose text does not include the filter
// text (ignore case)
filter.value = "ap";
filter.dispatchEvent(new Event("input"));
console.log(items.filter((li) => !li.hidden).map((li) => li.textContent).join(", "));

A comment form

Handle submit, validate emptiness and reset.

// On submit: prevent the default, ignore text that is empty after trim,
// otherwise add an li with the trimmed text to #comments and reset the form.
// Then submit "  Nice post! " and an empty comment, and log the count.

09Prediction

Commit to an answer first, then run the real code to compare.

// HTML: <form id="f"><input name="x"><button type="button" id="b">Go</button></form>
const f = document.getElementById("f");
f.addEventListener("submit", (e) => { e.preventDefault(); console.log("submit"); });
document.getElementById("b").click();
console.log("done");

What is printed?

10Debugging investigation

Pressing Enter does not add the item

Clicking Add works, but pressing Enter in the field reloads the page instead of adding the item.

const form = document.getElementById("f");
const list = document.getElementById("list");
document.getElementById("add").addEventListener("click", (event) => {
  event.preventDefault();
  const li = document.createElement("li");
  li.textContent = form.elements.entry.value;
  list.append(li);
});
form.requestSubmit();
console.log("Items: " + list.children.length);

More cases in the Debugging Detective Laboratory

11Practical scenario

Search as you type

Product search shows suggestions while you type (input, debounced), saves filters when a drop-down changes (change), and runs the full search when you press Enter (submit with preventDefault). Each event matches a different moment in the interaction.

const events = ["input", "input", "input", "change", "submit"];
console.log(events.map((e) => e === "input" ? "suggest" : e === "change" ? "save filter" : "search").join(" -> "));

12Knowledge check

1. Which event fires on every keystroke in a text field?

  • change
  • input
  • submit
  • blur

2. Where should you listen for a form being submitted?

  • click on the submit button
  • submit on the form
  • keydown on every input
  • change on the form

3. Why does clicking Clear submit the form?

<form>
  <input name="q">
  <button id="clear">Clear</button>
</form>
  • Buttons in forms default to type="submit"
  • Clear is a reserved word
  • click always submits
  • reset() submits

4. What does form.submit() skip that form.requestSubmit() does not?

  • Nothing
  • Validation and the submit event
  • Sending data
  • Resetting

5. A field has input and change listeners that log their names. The code sets value and dispatches input twice, then change once. What is logged?

  • input input change
  • change
  • input change
  • change input input

6. A search box calls a slow server. Which is better?

  • Call the server on every input event
  • Debounce input events, and search immediately on submit
  • Only search on page load
  • Poll the field every 10 ms

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • The form reloads the page: Prints Signed in as ada; signedIn is set; The default submission is cancelled
  • Live filter: Shows matching fruit; Empty filter shows all
  • A comment form: Prints 1; Text is trimmed; The form was reset

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-13-forms-and-validation/lesson-062-input-events-and-form-submission/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • input fires on every edit; change fires when the edit is committed.
  • Listen for submit on the form and call preventDefault.
  • requestSubmit simulates a real submission; buttons default to submit.
  • reset returns a form to its initial values.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation form events
Context: I am learning form events in JavaScript.
Task: Explain input, change and submit events and preventDefault with a small form.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction form events drill
Context: I have practised form events.
Task: Give me six form-event programs and ask what each logs and in which order.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging form events bug
Context: My form reloads the page whenever I press Enter.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation form events practice
Context: I finished the form events exercises.
Task: Create three exercises that use input, change and submit with exact expected output.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review form events review
Context: Here is my code that uses form events.
Task: Review my form handling code for click-instead-of-submit and missing preventDefault.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.