JavaScript 14 · Read a form without leaving the page

JavaScript lesson 14 of 50 · Early intermediate · About 35 minutes

Build a radio form that reads a made-up call sign and sends a local message.

Pip pauses where stone paths branch toward a crystal-roof workshop, a hanging garden and a distant beacon.
Mission Handle the submit event, validate a text field and display safe plain text.

Get ready

Open Complete checkpoint below. For a browser preview, put the HTML in your editor’s HTML panel and the JavaScript in its JavaScript panel. For a local file, put the HTML first in a new .html file, then put the JavaScript between <script> and </script> at the end. Save the file and open it in a browser.

Match the HTML to the JavaScript. HTML tags create the game’s controls and text. An id names one element. The code uses that name to find the element. A class groups elements for styling, while a data- attribute can carry a game value. A status area with aria-live lets compatible screen readers announce updates.

Submit the form. A click or the Enter key sends the event. → Validate the field. Trim spaces and check for an empty string. → Show the result. Update the report without navigating.
Submit the form → Validate the field → Show the result

Understand the JavaScript in this lesson

Language to look for forms and labels, submit event, preventDefault, input.value, trim, early return, focus.

1. Build a useful form

A label explains what to type. Its for matches the input’s id. The submit button sends the form when pressed, and Enter in the field can do the same. That is why we listen for submit on the form itself, instead of listening only for a mouse click.

form.addEventListener("submit", sendSignal);

2. Keep the interaction on this page

A form normally tries to navigate or send its fields when it is submitted. The event’s preventDefault() method cancels that usual action. This checkpoint uses the answer inside the current page. It reads a made-up call sign and never needs anyone’s real name.

event.preventDefault();

3. Get and check the typed text

An input element’s value is what the player typed. trim() removes spaces from the start and end so a line of spaces becomes an empty string. The === check detects that case. focus() returns the typing cursor to the field, and return leaves the function before the success line.

const callSign = input.value.trim();

4. Keep the answer as plain text

Join the call sign into the report sentence. Assigning the result through textContent tells the browser to show the typed characters as text. If a player types angle brackets, those characters remain part of the displayed words. The HTML structure stays the same.

report.textContent = "Dispatch received for " + callSign + ".";
Follow what happens step by step
  1. Submit a field containing only spaces.
    Enter a call sign first.Why Trimming produces an empty string, so the validation branch runs.
  2. Type a made-up call sign such as Comet and press Enter.
    Dispatch received for Comet.Why The form event reaches the listener even without a mouse click.

Predict before you run Why does the empty-field branch need return?

Reveal the answer

Without it, the function goes on to the success assignment. That would overwrite the useful validation message.

Complete checkpoint

HTML · the page and controls

<section aria-labelledby="mission-title">
  <h2 id="mission-title">Sky Island Rescue · Radio dispatch</h2>
  <form id="radio">
    <label for="call-sign">Invent a radio call sign</label>
    <input id="call-sign" name="callSign" maxlength="24" autocomplete="off">
    <button type="submit">Send to dispatch</button>
  </form>
  <p id="report" role="status">Dispatch is waiting.</p>
</section>

JavaScript · the instructions

const form = document.querySelector("#radio");
const input = document.querySelector("#call-sign");
const report = document.querySelector("#report");

function sendSignal(event) {
  event.preventDefault();
  const callSign = input.value.trim();

  if (callSign === "") {
    report.textContent = "Enter a call sign first.";
    input.focus();
    return;
  }

  report.textContent = "Dispatch received for " + callSign + ".";
}

form.addEventListener("submit", sendSignal);

Read the JavaScript line by line

Open a small group of lines while you read the complete checkpoint. Blank lines separate ideas. Closing braces mark the end of a block. An ellipsis here means you can read the rest in the full program.

Lines 1–18
Line 1 const form = document.querySelector("#radio");
Set up form. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 2 const input = document.querySelector("#call-sign");
Set up input. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 3 const report = document.querySelector("#report");
Set up report. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 5 function sendSignal(event) {
Define sendSignal. The body runs when the function is called, with inputs named event.
Line 6 event.preventDefault();
Stop the browser’s usual response to this event where permitted.
Line 7 const callSign = input.value.trim();
Set up callSign. Keep this name attached to the same value. Return text with whitespace removed from both ends.
Line 9 if (callSign === "") {
Run this part when the test is truthy. The triple equals compares without converting the value’s type.
Line 10 report.textContent = "Enter a call sign first.";
Replace the element’s displayed text. The browser treats the value as text.
Line 11 input.focus();
Give this control keyboard focus.
Line 12 return;
Leave this function immediately.
Line 15 report.textContent = "Dispatch received for " + callSign + ".";
Plus adds numbers or joins text, depending on its values. Replace the element’s displayed text. The browser treats the value as text.
Line 18 form.addEventListener("submit", sendSignal);
Register a function the browser should call when the named event happens.

Mission challenge

Test a call sign with spaces around it and another containing an angle bracket. Describe the displayed result.

Change one piece at a time. Run the checkpoint again and compare what you expected with what actually happened.