smartyfy.mrindigi.com

Web Development Pro | Lesson 029 | Form Handling and Client Feedback

Web Development Pro · Lesson 29 of 60

Module 3: JavaScript foundations

In this lesson

Prerequisites and learning outcomes

Complete lesson 28 first. This lesson builds on formdata, validation, and status messages. By the end, you can process a local demo form and show clear feedback without pretending to send it. Plan 10–15 minutes for the core explanation and additional time for the worked practice.

Handle the form's actual submission event

A person may submit a form by pressing Enter or activating its submit button. Listening only for a click on that button can miss other valid routes. Listen to the form's submit event instead. For this deliberately local demonstration, preventDefault stops the normal navigation so JavaScript can show a practice summary on the same page.

The interface must say what actually happened. It has not sent a registration, reserved a seat, or contacted an organizer. A local success message means only that the demonstration accepted the values under its rules. This distinction protects users from mistaking a polished interaction for a real service.

Read named values with FormData

FormData collects the form's eligible named controls using browser form rules. Its entries can be strings or files, depending on the controls. Our form uses only strings. A checkbox that is not checked may be absent, and a control without name may not contribute the key you expect. Inspect the actual keys rather than assuming labels are submitted.

const form = document.querySelector('#preference-form');
const status = document.querySelector('#form-status');
if (!form || !status) throw new Error('Preference form elements missing.');
form.addEventListener('submit', event => {
  event.preventDefault();
  if (!form.reportValidity()) return;
  const data = new FormData(form);
  const session = data.get('session');
  const rawSeats = data.get('seats');
  if (!['bicycle', 'mending'].includes(session) ||
      typeof rawSeats !== 'string' || rawSeats.trim() === '') {
    status.textContent = 'Choose a listed session and enter a seat count.';
    return;
  }
  const seats = Number(rawSeats);
  if (!Number.isInteger(seats) || seats < 1 || seats > 4) {
    status.textContent = 'Enter a whole number from 1 to 4.';
    return;
  }
  const label = session === 'bicycle' ? 'Bicycle basics' : 'Mending clothes';
  status.textContent = `Demo preference: ${seats} for ${label}. No booking was sent.`;
});

The complete HTML has required session and seats controls, numeric bounds, visible labels, and the matching names. ReportValidity asks the browser to check and report applicable native constraints. Under ordinary interactive submission, an invalid form may be stopped before submit fires, but the explicit check also documents the handler's expectation.

Convert only after checking meaning

Form values are strings, so the seat count needs conversion. Check for an empty trimmed string before Number, because Number('') is zero. Then require an integer in the accepted range. Each operation has a role: presence, conversion, numeric shape, and allowed bounds. Combining them carelessly can let an empty value masquerade as a real quantity.

The allowed session list is a local allowlist. A user can alter a select's options or send arbitrary values through other means, so do not assume that the visible choices are the only possible inputs. This local check improves consistency; a real server must independently validate the same kind of contract and enforce authorization and availability.

The conditional operator in label chooses one of two known display strings after validation. It has the form condition ? valueIfTrue : valueIfFalse. Use it for a small clear choice, not a deeply nested replacement for readable branches. The final message uses textContent, so the selected data is not interpreted as markup.

Keep feedback understandable and local

The status paragraph uses role="status" to support polite announcements of short updates. Do not move focus to it after every successful local preference unless the task requires that behavior. Preserving focus often lets the person continue or correct a value naturally. Test the actual announcement and focus experience in a browser with appropriate assistive technology.

When a value is rejected, preserve the other fields. Clearing the entire form forces the person to repeat correct work and can make recovery frustrating. Also distinguish a field error from a service failure. This example has no network service, so it cannot honestly produce a “server accepted” result or diagnose a delivery failure.

Do not disable a submit button merely because the form is currently incomplete without considering how users will discover what is missing. Native validation triggered by an available submit action can be easier to understand. If a real asynchronous submission later disables controls while sending, it needs clear loading, failure, retry, and duplicate-submission behavior.

Know the limits of client-side control

PreventDefault is not a security boundary. A browser user can bypass your handler, change the page, or construct a request independently. HTTPS protects transport but does not make submitted values trustworthy. Never put private API credentials into a client-side form script to make it “send directly” to an administrative service.

For this exercise, the form's HTML action points to a local explanatory preview if JavaScript is unavailable. With the handler running, no navigation occurs and the local status is updated. The fallback should also state that no booking happened. Progressive enhancement must preserve honest behavior in both paths.

Test more than one activation

Test valid values, an unlisted session, empty seats, zero, a fraction, the upper bound four, and five. Submit the same values twice and confirm the message is replaced rather than duplicated. Then verify in a real browser that Enter and the submit button reach the same intended handler and that native invalid states are understandable.

The supplied runtime fixture models FormData with explicit string entries and stubs reportValidity. It checks the handler's own branches and that preventDefault was called. It does not implement the browser's native validation algorithm or real FormData construction, so those behaviors remain manual browser checks.

Worked practice

Worked exercise 1: Catch keyboard submission

Task: A form only listens for a button click and misses an Enter-based submission path. Worked answer: attach the handler to form.addEventListener('submit', ...). Keep the submit button native and use preventDefault only because this workflow is intentionally local.

Worked exercise 2: Reject whitespace

Task: The seats value is three spaces. Worked answer: trim it and reject the empty result before conversion. Number on whitespace would produce zero, which hides the distinction between missing input and a genuine numeric entry.

Worked exercise 3: Test an altered option

Task: FormData contains session='private-room', which was never offered. Worked answer: reject it using the allowed session values and show a useful correction. A real server must repeat that validation; the local select's original options are not an authorization guarantee.

Knowledge check

Question 1

Which event best represents the form submission workflow? A) A click on one specific button only. B) submit on the form. C) keydown for Enter on the input as the only submission path. D) change on each field as a substitute for submitting.

Check question 1: answer and explanation

Answer: B. Submit covers the form-level action across ordinary activation routes.

Question 2

Why check trimmed emptiness before Number? A) Empty or whitespace strings can convert to zero. B) Number preserves an empty value as a distinct missing-input type. C) FormData converts number controls to numbers already. D) Trimming alone establishes that every remaining character is numeric.

Check question 2: answer and explanation

Answer: A. Presence and numeric conversion answer different questions.

Question 3

What does the session allowlist protect in this demo? A) Authorization for every request independently sent to a real server. B) The number of seats still available to other visitors. C) The handler's accepted local value contract. D) All requests made after a user changes the client code.

Check question 3: answer and explanation

Answer: C. Client checks cannot enforce a server's security boundary.

Question 4

What should the local success message claim? A) A booking is guaranteed because browser validation passed. B) The session is available because it appears in the select options. C) The submitted preference was saved for a future visit. D) A demo preference was processed without sending a booking.

Check question 4: answer and explanation

Answer: D. Feedback must match the implemented effect.

Question 5

What does the fixture's reportValidity stub leave untested? A) Actual native constraint validation and its browser feedback. B) The handler's explicit range branches. C) Whether preventDefault was invoked. D) The final text assignment.

Check question 5: answer and explanation

Answer: A. A stubbed result is not an execution of the browser's validation engine.

Sources and further reading