OnlineCBT Logo OnlineCBT
JavaScript Tutorial
JAVASCRIPT · LESSON 22

Form Handling and Event Prevention (preventDefault)

By Ratan Updated: 16 Oct 2026

Intercept form submissions, validate inputs, and prevent page refreshes with e.preventDefault().

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

Handle the form's submit event

Listen on the form rather than only a button click so keyboard submission follows the same validation path. preventDefault cancels the browser's normal submission when the event is cancelable; it does not validate data or send a request by itself.

Enter Asha and 82, then submit: expect Asha: 82. Native input constraints provide initial checks; the handler also validates its own requirements. Required does not reject a string containing only spaces, so the trimmed name check matters.

FormData details

Controls need a name to contribute values. Disabled controls and unchecked checkboxes have special submission behavior; do not assume every visible field appears. Use getAll when repeated controls share a name. A button with no explicit type inside a form defaults to submit, so auxiliary controls should use type=button.

Client checks are not enforcement

The server must validate again and derive identity/permissions from trusted authentication. A user can bypass the UI. For an async submission, show pending state, avoid accidental duplicate actions and restore controls after failure. A disabled button alone cannot guarantee one server-side write.

Practice

  1. Submit by pressing Enter in a field.
  2. Test whitespace-only name, score zero and invalid score 101.
  3. Add a Reset button with an explicit type and verify its intended behavior.
  4. Explain why preventDefault does not stop event propagation or save data automatically.

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat