📘 Lesson  ·  Lesson 38

Form Handling

Form Handling

The submit Event — and preventDefault

<form id="myForm">
    <input type="text" id="name">
    <button type="submit">Send</button>
</form>
let form = document.querySelector("#myForm");

form.addEventListener("submit", function(e) {
    e.preventDefault();          // ← STOP the page from reloading
    console.log("Form submitted, handling it with JavaScript");
});
Listen for submit on the FORM element (not click on the button) — this catches both button clicks and the Enter key. Then immediately call e.preventDefault(). Without it, the browser's default behaviour kicks in: the page reloads, and your JavaScript never runs. These two lines are the opening of nearly every form script you will ever write. Once the default is prevented, the form is yours to validate, read, and send however you like.

Reading Form Values

let name  = document.querySelector("#name").value;         // text → string
let email = document.querySelector("#email").value.trim(); // trim the spaces!
let age   = Number(document.querySelector("#age").value);  // convert to number

let agreed  = document.querySelector("#terms").checked;    // checkbox → boolean
let city    = document.querySelector("#citySelect").value; // select → the option's value
let gender  = document.querySelector("input[name='gender']:checked").value;  // radio
Three habits make form reading reliable. First, .value is always a STRING — wrap numeric inputs in Number() before doing maths. Second, always .trim() text input, because users constantly leave stray spaces (recall the string methods chapter). Third, checkboxes use .checked (a boolean), not .value. Radio buttons need the :checked selector to find the selected one. Get these right and most form bugs disappear before they start.

Basic Validation

form.addEventListener("submit", function(e) {
    e.preventDefault();

    let name = document.querySelector("#name").value.trim();
    let email = document.querySelector("#email").value.trim();
    let age = Number(document.querySelector("#age").value);

    if (name === "") {
        alert("Name is required");
        return;                        // early return — stop here
    }
    if (!email.includes("@")) {
        alert("Please enter a valid email");
        return;
    }
    if (age < 18) {
        alert("You must be 18 or older");
        return;
    }

    console.log("All valid! Sending:", { name, email, age });
});
Validation is simply a series of if checks, each with an early return to stop processing when something is wrong. Notice how naturally the pieces fit: trim() and includes() from strings, guard clauses from the return chapter, Number() from type conversion. An empty string is falsy, so if (!name) works too. Note that browser-side validation is for USER CONVENIENCE only — it can be bypassed, so the server must always validate again. Never trust the front end for security.

Showing Error Messages Properly

<input type="text" id="name">
<span class="error" id="nameError"></span>
function showError(id, message) {
    document.querySelector(id).textContent = message;   // textContent = safe
}

if (name === "") {
    showError("#nameError", "Name is required");
    document.querySelector("#name").classList.add("invalid");   // red border via CSS
    return;
}
showError("#nameError", "");     // clear the error when valid
Real forms don't use alert() — they show inline messages next to the offending field. Put an empty <span> beside each input, and fill it with textContent when validation fails (using textContent, not innerHTML, keeps it safe). Add an .invalid class to give the input a red border via CSS — the classList approach from earlier. And remember to CLEAR old messages when the user fixes the problem, or stale errors linger.

A Complete Example — everything together

const form = document.querySelector("#signupForm");
const list = document.querySelector("#userList");

form.addEventListener("submit", function(e) {
    e.preventDefault();

    const name = document.querySelector("#name").value.trim();
    const errorEl = document.querySelector("#nameError");

    if (!name) {                                  // empty string is falsy
        errorEl.textContent = "Please enter a name";
        return;
    }
    errorEl.textContent = "";                     // clear any old error

    const li = document.createElement("li");      // build a new element
    li.textContent = name;
    list.appendChild(li);                         // add it to the page

    form.reset();                                 // clear the form fields
});
This small script uses almost every DOM skill from this group: selecting elements, listening for submit, preventDefault(), reading and trimming .value, guard-clause validation, setting textContent, creating an element, and appending it to the page. form.reset() clears all fields afterwards. Read it line by line — this is what a real feature looks like. With the DOM and events complete, you can now build genuinely interactive pages.

Exam Corner

Q: Which event should you listen for on a form, and why? submit — it catches both button clicks and the Enter key.

Q: What is the first line of almost every form handler? e.preventDefault(); to stop the page reloading.

Q: How do you read a checkbox's state? With .checked, which returns a boolean.

Q: Why trim() text input? Users often type accidental leading or trailing spaces.

Q: Is client-side validation enough for security? No — it can be bypassed; the server must validate too.

submit Event — और preventDefault

<form id="myForm">
    <input type="text" id="name">
    <button type="submit">Send</button>
</form>
let form = document.querySelector("#myForm");

form.addEventListener("submit", function(e) {
    e.preventDefault();          // ← page ko reload hone se ROKO
    console.log("Form submit hua, JavaScript se handle kar rahe");
});
FORM element पर submit सुनिए (button पर click नहीं) — यह button clicks और Enter key दोनों पकड़ता है. फिर तुरंत e.preventDefault() call कीजिए. इसके बिना, browser का default व्यवहार शुरू होता है: page reload होता है, और आपका JavaScript कभी नहीं चलता. ये दो lines लगभग हर form script की शुरुआत हैं जो आप कभी लिखेंगे. Default रुकने के बाद, form आपका है validate, पढ़ने, और जैसे चाहें भेजने को.

Form Values पढ़ना

let name  = document.querySelector("#name").value;         // text → string
let email = document.querySelector("#email").value.trim(); // spaces trim karo!
let age   = Number(document.querySelector("#age").value);  // number me badlo

let agreed  = document.querySelector("#terms").checked;    // checkbox → boolean
let city    = document.querySelector("#citySelect").value; // select → option ki value
let gender  = document.querySelector("input[name='gender']:checked").value;  // radio
तीन आदतें form पढ़ना भरोसेमंद बनाती हैं. पहली, .value हमेशा STRING है — गणित से पहले numeric inputs को Number() में लपेटिए. दूसरी, text input हमेशा .trim() कीजिए, क्योंकि users लगातार भटके spaces छोड़ते हैं (string methods chapter याद कीजिए). तीसरी, checkboxes .checked use करते हैं (boolean), .value नहीं. Radio buttons को चुना हुआ ढूंढने को :checked selector चाहिए. ये सही कीजिए और ज़्यादातर form bugs शुरू होने से पहले गायब हो जाते हैं.

बुनियादी Validation

form.addEventListener("submit", function(e) {
    e.preventDefault();

    let name = document.querySelector("#name").value.trim();
    let email = document.querySelector("#email").value.trim();
    let age = Number(document.querySelector("#age").value);

    if (name === "") {
        alert("Name is required");
        return;                        // early return — yahin ruko
    }
    if (!email.includes("@")) {
        alert("Please enter a valid email");
        return;
    }
    if (age < 18) {
        alert("You must be 18 or older");
        return;
    }

    console.log("All valid! Sending:", { name, email, age });
});
Validation बस if जांचों की श्रृंखला है, हर एक के साथ early return ताकि कुछ गलत हो तो processing रुके. ध्यान दीजिए टुकड़े कितनी स्वाभाविकता से बैठते हैं: strings से trim() और includes(), return chapter से guard clauses, type conversion से Number(). खाली string falsy है, तो if (!name) भी चलता है. ध्यान दीजिए browser-side validation सिर्फ USER की सुविधा के लिए है — इसे bypass किया जा सकता है, तो server को हमेशा दोबारा validate करना चाहिए. Security के लिए front end पर कभी भरोसा मत कीजिए.

Error Messages ठीक से दिखाना

<input type="text" id="name">
<span class="error" id="nameError"></span>
function showError(id, message) {
    document.querySelector(id).textContent = message;   // textContent = surakshit
}

if (name === "") {
    showError("#nameError", "Name is required");
    document.querySelector("#name").classList.add("invalid");   // CSS se laal border
    return;
}
showError("#nameError", "");     // valid hone par error saaf karo
असली forms alert() use नहीं करते — वे गलत field के पास inline messages दिखाते हैं. हर input के बगल में खाली <span> रखिए, और validation fail होने पर उसे textContent से भरिए (textContent, न कि innerHTML, इसे सुरक्षित रखता है). Input को CSS से लाल border देने को .invalid class जोड़िए — पहले वाला classList approach. और user के problem ठीक करने पर पुराने messages SAAF करना याद रखिए, वरना बासी errors टिके रहते हैं.

पूरा Example — सब कुछ साथ

const form = document.querySelector("#signupForm");
const list = document.querySelector("#userList");

form.addEventListener("submit", function(e) {
    e.preventDefault();

    const name = document.querySelector("#name").value.trim();
    const errorEl = document.querySelector("#nameError");

    if (!name) {                                  // khali string falsy hai
        errorEl.textContent = "Please enter a name";
        return;
    }
    errorEl.textContent = "";                     // purana error saaf karo

    const li = document.createElement("li");      // naya element banao
    li.textContent = name;
    list.appendChild(li);                         // page me jodo

    form.reset();                                 // form fields saaf karo
});
यह छोटी script इस group का लगभग हर DOM skill use करती है: elements select करना, submit सुनना, preventDefault(), .value पढ़ना और trim करना, guard-clause validation, textContent set करना, element बनाना, और page में जोड़ना. form.reset() बाद में सारे fields साफ करता है. Line-दर-line पढ़िए — असली feature ऐसी दिखती है. DOM और events पूरे होने से, अब आप सच में interactive pages बना सकते हैं.

Exam Corner

Q: Form पर कौन-सा event सुनना चाहिए, और क्यों? submit — यह button clicks और Enter key दोनों पकड़ता है.

Q: लगभग हर form handler की पहली line क्या है? e.preventDefault(); page reload रोकने को.

Q: Checkbox की state कैसे पढ़ते हैं? .checked से, जो boolean लौटाता है.

Q: Text input trim() क्यों करें? Users अक्सर गलती से आगे-पीछे spaces type करते हैं.

Q: क्या client-side validation security के लिए काफी है? नहीं — इसे bypass किया जा सकता है; server को भी validate करना चाहिए.
← Back to JavaScript Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

इस पेज का code यहाँ तैयार है — बदलिए और तुरंत नतीजा देखिए. कुछ install किए बिना.
👁 Live Preview
सब कुछ आपके browser में ही चलता है — कोई server, कोई signup नहीं. JavaScript का console.log देखने के लिए F12 दबाइए.