Lesson 2: Handling User Input

Learning Objectives

By the end of this lesson, learners will be able to:

  • Capture and respond to user input in text fields and forms
  • Use the .value property to access input content
  • React in real-time to typing with the input event
  • Validate input using basic checks (e.g., required, empty)
  • Update the page dynamically based on user data

Why This Matters

User input is the heart of interactivity on websites. Forms, search bars, chats, signups—almost everything involves letting users type and respond to what they typed.

JavaScript allows you to:

  • Read what the user types
  • Validate it
  • Respond by updating the page or giving feedback

Accessing User Input with .value

Use the .value property on input elements to get what the user typed.

Example:

<input id="name-input" type="text" placeholder="Enter your name" />
let input = document.getElementById("name-input");
let name = input.value; // returns the current text in the field

Responding to Input in Real-Time

The input event lets you respond as the user types:

Example:

<input id="live-input" placeholder="Type something..." />
<p id="display-text"></p>
let input = document.getElementById("live-input");
let display = document.getElementById("display-text");

input.addEventListener("input", function () {
  display.textContent = "You typed: " + input.value;
});

This provides instant feedback, useful in live previews or search suggestions.


Validating Input (Basic Checks)

Before using the input, always validate it.

Common validations:

  • Check if the field is empty
  • Use .trim() to remove whitespace
  • Ensure the input matches expected data (e.g., number, email)

Example:

let name = input.value.trim();

if (name === "") {
  alert("Please enter your name.");
}

Example: Personalized Greeting

HTML:

<input id="username" type="text" placeholder="Your name" />
<button id="greet-btn">Say Hello</button>
<p id="greeting"></p>

JavaScript:

let input = document.getElementById("username");
let button = document.getElementById("greet-btn");
let output = document.getElementById("greeting");

button.addEventListener("click", function () {
  let name = input.value.trim();

  if (name === "") {
    output.textContent = "Please enter your name.";
    output.style.color = "red";
  } else {
    output.textContent = "Hello, " + name + "!";
    output.style.color = "green";
  }
});

This demonstrates:

  • Reading input from a field
  • Checking for empty input
  • Displaying dynamic feedback

Summary

ConceptDescription
.valueGets the current input from a text field
input eventFires as the user types
.trim()Removes leading/trailing whitespace
Dynamic feedbackUpdate the DOM with user data