5.1 Module 5 · Forms & Input Handling

Form Data Handling

Learn how to read values from inputs, set them programmatically, and work with text areas, select boxes, and checkboxes — the foundation of every interactive form on the web.

1

Definition

Form Data Handling in JavaScript refers to the process of accessing, reading, and modifying user input values from HTML form elements such as text inputs, textareas, checkboxes, radio buttons, and select boxes using the DOM.

Every interactive form on the web — login, registration, checkout, search — relies on this: JavaScript reads what the user typed or selected, processes it, and responds accordingly.

2

Simple Way

Form data handling means "taking input from the user and using it in JavaScript". Three fundamental operations:

.value Read what the user typed — works on any input, textarea, or select
.value = Write a value into the input — autofill, defaults, or edit-form pre-population
.checked Read or set whether a checkbox or radio button is selected
.trim() Remove accidental leading/trailing spaces from the user's input before using it
3

Code Examples

Example 1 — Reading Input Value (.value)
<input id="username" type="text" value="Aman">
<button onclick="readValue()">Get Value</button>
<p id="out1"></p>

<script>
  function readValue() {
    let input = document.getElementById("username");
    let name  = input.value.trim(); // trim removes extra spaces
    document.getElementById("out1").textContent = "You entered: " + name;
  }
</script>
Live Preview
Explanation
  • .value is a property — not a method — that returns whatever the user has typed
  • It always returns a string, even if the user typed a number
  • .trim() removes leading/trailing whitespace — always call it before validation
Example 2 — Setting Input Value Programmatically
<input id="nameField" type="text" placeholder="Your name...">
<button onclick="setDefault()">Auto Fill</button>
<button onclick="clearField()">Clear</button>

<script>
  function setDefault() {
    document.getElementById("nameField").value = "Aman Raj";
  }

  function clearField() {
    document.getElementById("nameField").value = "";
  }
</script>
Live Preview
Explanation
  • Assigning to .value sets the input's content — the user sees the change immediately
  • Assigning an empty string "" clears the field
  • Common uses: autofill from saved data, populating edit forms, resetting after submit
Example 3 — Textarea & Select Box
<textarea id="bio" rows="3" placeholder="Write your bio..."></textarea>
<select id="country">
  <option value="in">India</option>
  <option value="us">USA</option>
  <option value="uk">UK</option>
</select>
<button onclick="readForm()">Read</button>
<p id="out3"></p>

<script>
  function readForm() {
    let bio     = document.getElementById("bio").value.trim();
    let country = document.getElementById("country").value;
    document.getElementById("out3").textContent =
      "Bio: " + (bio || "(empty)") + " | Country: " + country;
  }
</script>
Live Preview
Explanation
  • textarea.value works exactly like input.value — reads multi-line text
  • select.value returns the value attribute of the currently selected option
  • All form elements share the .value interface — the same pattern works everywhere
Example 4 — Checkbox & Radio Button
<label>
  <input id="agree" type="checkbox"> I agree to terms
</label><br>
<label><input name="plan" type="radio" value="free"> Free</label>
<label><input name="plan" type="radio" value="pro"> Pro</label>
<button onclick="readChoices()">Check</button>
<p id="out4"></p>

<script>
  function readChoices() {
    let agreed = document.getElementById("agree").checked;
    let plan   = document.querySelector('input[name="plan"]:checked');
    document.getElementById("out4").textContent =
      "Agreed: " + agreed + " | Plan: " + (plan ? plan.value : "none");
  }
</script>
Live Preview
Explanation
  • checkbox.checked returns true or false
  • For radio buttons, use querySelector('input[name="plan"]:checked') to find whichever is selected
  • Radio and checkbox inputs do not use .value for their selected state — .checked is the correct property
4

Real-Life Example

Think of a hotel check-in desk — the receptionist handles data exactly like JavaScript handles form data:

.value (read)
Guest writes their name — receptionist reads and records it
.value = (write)
Receptionist pre-fills the form with details from the booking system
.trim()
Receptionist ignores extra spaces the guest typed at the start or end
.checked
Checking whether the "Breakfast included?" box is ticked or not
5

HTML + JavaScript Example

Click ▶ Preview — type a name, click Show Name to read it, or click Auto Fill to write a default value programmatically.

Live in Browser — Read & Write Form Data
<!DOCTYPE html>
<html>
<head><title>Form Data Handling</title></head>
<body style="font-family:sans-serif;padding:24px;background:#f8f9fa">

  <h2>Enter Your Name</h2>

  <input id="nameInput" type="text" placeholder="Type your name..."
    style="padding:8px 12px;border:1px solid #ccc;border-radius:6px;
           font-size:1rem;width:220px">

  <div style="display:flex;gap:8px;margin-top:12px;flex-wrap:wrap">
    <button onclick="showName()"
      style="padding:8px 16px;background:#f7df1e;border:none;border-radius:6px;
             cursor:pointer;font-weight:700">
      Show Name
    </button>
    <button onclick="autoFill()"
      style="padding:8px 16px;background:#4ade80;border:none;border-radius:6px;
             cursor:pointer;font-weight:700">
      Auto Fill
    </button>
    <button onclick="clearInput()"
      style="padding:8px 16px;background:#f87171;border:none;border-radius:6px;
             cursor:pointer;font-weight:700;color:#fff">
      Clear
    </button>
  </div>

  <div id="output" style="margin-top:16px;font-size:0.95rem;line-height:2"></div>

  <script>
    function showName() {
      let raw  = document.getElementById("nameInput").value;
      let name = raw.trim();
      let out  = document.getElementById("output");

      if (!name) {
        out.innerHTML = "<b style='color:red'>Please enter a name.</b>";
        return;
      }
      out.innerHTML =
        "<b>Raw value:</b> "" + raw + ""<br>" +
        "<b>Trimmed:</b> "" + name + ""<br>" +
        "<b>Length:</b> " + name.length + " characters";
    }

    function autoFill() {
      document.getElementById("nameInput").value = "Aman Raj";
      document.getElementById("output").textContent = "Auto-filled with: Aman Raj";
    }

    function clearInput() {
      document.getElementById("nameInput").value = "";
      document.getElementById("output").textContent = "Field cleared.";
    }
  </script>

</body>
</html>
Live Preview
6

Tasks (Practice)

Easy Task 1 — Read email input
Starter code
<input id="emailField" type="text" placeholder="Enter email">
<button onclick="readEmail()">Get Email</button>

<script>
  function readEmail() {
    // read the value and print it to the console
  }
</script>
  • Use getElementById("emailField").value to read the input
  • Call .trim() before using the value
  • Print the email using console.log()
Medium Task 2 — Auto-fill default username
Starter code
<input id="usernameField" type="text" placeholder="Username">
<button onclick="fillDefault()">Fill Default Name</button>

<script>
  function fillDefault() {
    // set the value to "Guest User"
  }
</script>
  • Set usernameField.value = "Guest User" when the button is clicked
  • Add a second button that clears the field
  • Display a confirmation message below the input using a <p> element
7

MCQs

Q1
How do you read the current value of an input field?
<input id="test" type="text" value="Hello">
<script>
  let el = document.getElementById("test");
  console.log(el.value);
</script>
Live Preview
  • A .text
  • B .value
  • C .innerHTML
  • D .getValue()
💡 B is correct. .value is the standard property for reading and writing the content of any form input. .innerHTML is for element content, not input values — it does not work on inputs.
Q2
Which method is the fastest way to select an element by its id?
  • A querySelectorAll()
  • B getElementById()
  • C getElementsByClass()
  • D selectById()
💡 B is correct. getElementById() is optimised specifically for ID lookup — it is the fastest DOM selector. getElementsByClass() is not a real method; the correct name is getElementsByClassName().
Q3
What does this line do?
document.getElementById("myInput").value = "Hello";
Output
Click ▶ Run to execute
  • A Gets the current value of the input
  • B Deletes the input's value
  • C Sets the input's value to "Hello"
  • D Logs the value to the console
💡 C is correct. Assigning to .value sets the displayed content of the input field. The user will see "Hello" in the input immediately — the same as if they had typed it.
8

Pro Tips & Extra Knowledge

  • 01

    Always call .trim() before using input data — users commonly type extra spaces and your validation logic will fail silently without it:

    trim() prevents hidden space bugs
    let raw  = "  Aman  "; // user typed with spaces
    let name = raw.trim(); // "Aman"
    
    console.log(raw  === "Aman"); // false — spaces break the comparison
    console.log(name === "Aman"); // true  — safe to use
    Output
    Click ▶ Run to execute
  • 02

    Always check that the element exists before reading its .value — accessing a property on null throws an error:

    Null check before access
    let el = document.getElementById("mayNotExist");
    
    // ✗ Dangerous — throws TypeError if el is null
    // console.log(el.value);
    
    // ✓ Safe — check first
    if (el) {
      console.log(el.value);
    } else {
      console.log("Element not found");
    }
    
    // Modern shorthand (optional chaining)
    console.log(el?.value ?? "Element not found");
    Output
    Click ▶ Run to execute
  • 03

    Remember that .value always returns a string — convert it before doing any arithmetic:

    .value is always a string
    // Simulating input.value from a number field
    let raw = "25"; // .value always returns string
    
    console.log(raw + 5);           // "255" — string concatenation!
    console.log(Number(raw) + 5);   // 30   — correct arithmetic
    Output
    Click ▶ Run to execute
  • 04

    Use querySelector() for flexible selection — it accepts any CSS selector and is consistent across all element types:

    querySelector for flexible selection
    // Both select the same element — querySelector is more flexible
    let byId  = document.getElementById("username");
    let byQS  = document.querySelector("#username");
    
    // querySelector can do things getElementById cannot:
    let firstInput     = document.querySelector("input[type='text']");
    let checkedRadio   = document.querySelector("input[name='plan']:checked");
    let lastListItem   = document.querySelector("ul li:last-child");
    
    console.log(typeof byId);   // "object"
    console.log(typeof byQS);   // "object" — same result
    Output
    Click ▶ Run to execute
Mini Challenge

The input has a pre-set value — what does each log print, and what type is it? Think before running.

What does this print?
<input id="ageInput" type="number" value="25">

<script>
  let input = document.getElementById("ageInput");
  let raw   = input.value;

  console.log(raw);
  console.log(typeof raw);
  console.log(raw + 5);
  console.log(Number(raw) + 5);
</script>
Live Preview
Step-by-Step Explanation
// input.value always returns a STRING — even for type="number"

// Line 1: console.log(raw)
//   raw = "25"  (string)
//   Output → "25"

// Line 2: console.log(typeof raw)
//   typeof "25" === "string"
//   Output → "string"

// Line 3: console.log(raw + 5)
//   "25" + 5 → string concatenation (+ with a string)
//   Output → "255"   ← NOT 30!

// Line 4: console.log(Number(raw) + 5)
//   Number("25") = 25 (number)
//   25 + 5 = 30
//   Output → 30   ← correct arithmetic

// Final output:
//   "25"
//   "string"
//   "255"
//   30

// Key takeaway:
//   ALWAYS convert with Number() before arithmetic on form values
//   even when the input type is "number"