Skip to content

Form Event Handling

Website Screenshot

At the end of this class, you should be able to…

  • Implement event listeners for form submissions using the submit event.
  • Access and manipulate form input values using JavaScript.
  • Prevent default form behavior to enable custom form processing.

Additional Notes: Students must read chapter 11 of JSFBP


In-Class Demo Jan 2026 term

To run the coding demo, you need to have your Student Workbook open in Visual Studio Code.

  1. Open the terminal window and paste in the following.

    Run from the root of your repository
    pnpm dlx tiged --disable-cache --force DG-InClass/SDEV-1150-A04-Jan-2026/sk/lesson-10 ./src/lesson-10
  2. Walk through the steps in the ReadMe.md of the new lesson.


Complete the demo along with your instructor and then attempt the exercise prompts (see the comments in the main.js file).

This lesson walks through working with forms: reading values, gathering checkbox/radio inputs, handling submit (preventing default navigation), and showing a structured summary of form data.

const form = document.querySelector('#contact-form');
const result = document.querySelector('#result');
function serializeForm(formEl) {
// Access inputs from form.elements
const { fullName, email, bio } = formEl.elements;
// Radio value
const plan = formEl.elements.plan.value;
// Checkboxes: gather checked values
const topics = Array.from(formEl.querySelectorAll('input[name="topics"]:checked'))
.map(cb => cb.value);
return {
fullName: fullName.value.trim(),
email: email.value.trim(),
plan,
topics,
bio: bio.value.trim(),
submittedAt: new Date().toLocaleString(),
};
}

Handle form submission (prevent page reload)

Section titled “Handle form submission (prevent page reload)”
form.addEventListener('submit', (event) => {
event.preventDefault(); // stop form from navigating/reloading
const data = serializeForm(form);
result.textContent =
`Submission received:
- Name: ${data.fullName || '(none)'}
- Email: ${data.email || '(none)'}
- Skill: ${data.plan || '(none)'}
- Strengths: ${data.topics.length ? data.topics.join(', ') : '(none)'}
- Bio: ${data.bio || '(none)'}
- Time: ${data.submittedAt}`;
});
form.addEventListener('reset', () => {
result.textContent = 'Awaiting submission...';
});

Once you’re done making your own custom updates to the project, stage your files, commit your work, and push to the remote repository.

  1. Open a terminal in VS Code
  2. Stage all updated and created files:
Terminal window
git add .
  1. Commit the changes:
Terminal window
git commit -m 'Lesson 10 Example'
  1. Push your changes to the remote workbook repository:
Terminal window
git push origin main