Volume 2 Companion: The Web FrontendPractice for Volume 2
0 / 0

Workbench / Volume 2 Companion: The Web Frontend

V2·13

HTML

Companion to Volume 2, chapter 13: how document structure, built-in semantics and forms connect; new angles (HTML as a contract with three readers, a form as a printed order slip, landmarks as signboards in a railway station); what the chapter simplifies, from a form that sends "₹" as `₹` when the page forgets its charset to Enter submitting a one-field form but not a two-field one, a number field that sends `1e1` to the server, and `maxlength` counting emoji as two; the theory behind it (least power, the principle of graceful failure, why HTML is forgiving and forms are strict); how the URL standard's form encoder is written; four debugging drills; interview questions with how to approach each.

6 sections · ~17 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 13 has three strands. Document structure: the skeleton every page needs, headings and landmarks that give it an outline, text semantics, links and buttons, images and tables. Semantics and behaviour: elements come with implicit roles and default behaviour (focus, keyboard, submission), constrained by content models, which is what the accessibility tree is built from; ARIA patches the gaps HTML can't fill. Forms and loading: forms collect and submit data with no script at all, using typed inputs, labels and built-in validation; and HTML decides how scripts and resources load.

document structure semantics and behaviour forms and loading skeleton, metadata doctype · charset · viewport headings, landmarks the page's outline text semantics em · strong · time · lists links and buttons go somewhere · do something images alt · sizes · lazy tables data, with headers implicit semantics elements come with roles content models what may nest in what default behaviour focus · keys · submission accessibility the radio script ARIA only when HTML can't media, embeds, SVG iframe · video · canvas form submission GET · POST · encodings input types number · email · date labels, fieldsets names for controls validation constraints · messages FormData, multipart files · JS submission loading scripts defer · async · modules then inside plus plus plus constrained by gives feeds patched by made of named by checked by then sent as goes deeper: ch12 parsing and encodings · ch20 accessibility · ch27 loading performance · ch28 security exercises: P1–P12 build pages, forms, tables and dialogs and measure what the browser does with them
Concept map of chapter 13, HTML: document structure (the skeleton and metadata, headings and landmarks, text semantics, links and buttons, images, tables), semantics and behaviour (implicit semantics, content models, default browser behaviour, accessibility, media and embeds) and forms and loading (form submission, input types, labels and fieldsets, validation, FormData and multipart, and loading scripts with async, defer, modules and preload), with links such as semantic elements giving implicit roles to the accessibility tree and forms submitting without any script.

The links worth remembering:

  • Choosing the right element gives you behaviour for free. A <button> is focusable, activates with Enter and Space, has the role "button", and submits its form. A <div onclick> has none of that, and every missing piece has to be rebuilt in JavaScript (badly). Most of the chapter is a catalogue of free behaviour.
  • Forms are a protocol, not just markup. A form's markup decides the HTTP request the browser builds: method, encoding, names and values. The server receives exactly what the form describes, so the HTML and the server's parser have to agree (Gaps 1 and 3).
  • Client-side validation is for people; server-side validation is for correctness. Built-in constraints save users a round trip, but anyone can send any request. Everything the form checks, the server must check again.

Explain it differently

1. HTML is a contract with three readers. The browser reads it to draw and behave; assistive technology reads it (through the accessibility tree) to speak and navigate; machines (search engines, link previews, password managers, translation tools) read it to understand. A <div> styled to look like a heading satisfies only the first reader. Semantic HTML is writing for all three at once.

2. A form is a printed order slip. The slip has labelled boxes (inputs with labels), some marked "required", some that only accept numbers. You hand it to the counter (submit), and the clerk reads each box by its label (the name attribute). Boxes without a printed label (no name) aren't read at all, and a box labelled twice sends two values. The browser fills in the slip's envelope (method, encoding) from the form's attributes.

3. Landmarks are the signboards in a railway station. A sighted traveller scans the station; a screen-reader user jumps between signboards: "main", "navigation", "search", "footer". Pages with landmarks (<header>, <nav>, <main>, <footer>, <search>) let users skip straight to the menu or the cart. Pages without them make users walk past every stall.

4. Links go somewhere; buttons do something. A link changes the URL: it can be bookmarked, opened in a new tab, shared, and the back button undoes it. A button performs an action on the current page: submit, add to cart, open a dialog. Using one as the other breaks behaviour users rely on (middle-click on a "link" that's really a button does nothing; the back button after a "button" that navigates goes somewhere unexpected).

5. Content models are grammar rules for elements. Just as a sentence can't contain a full stop in the middle of a word, a <p> can't contain a <div>, and a <button> can't contain another interactive element. The HTML parser enforces some rules by rewriting your markup (closing the <p> before the <div>), and silently ignores others, so invalid HTML doesn't fail, it changes meaning (Chapter Exercises P1).

6. alt text is what you'd say on the phone. If you were describing the page to someone over a call, what would you say about each image? A photo of a dosa that's the main subject: "masala dosa with sambar and two chutneys". A decorative divider: nothing (alt=""). A logo that's a link home: "TiffinBox home". The test is the purpose of the image, not its appearance.

7. Implicit submission is a keyboard shortcut with rules. Pressing Enter in a text field submits the form, but only under conditions the specification spells out: there's a submit button, or the form has only one field that blocks it (Gaps 2). It's a convenience designed for search boxes, and it has surprised generations of developers building multi-field forms.

8. defer and async are two ways to stand in a queue. A classic <script> makes the parser stop and wait at the counter until the script is fetched and run. defer takes a ticket: download in the background, run in order after the document is parsed. async also downloads in the background, but runs the moment it's ready, in any order, interrupting the parser. Modules are deferred by default. Picking the right one is the difference between a page that renders at once and one that waits for every script.

Gaps and misconceptions

What the chapter oversimplifies

1. "Forms submit UTF-8": only from pages that are UTF-8. The chapter shows forms sending percent-encoded UTF-8. The encoding a form submits in is the page's encoding. Submitting "₹40 మసాలా" from two pages that differ only in their charset (real output, Chromium):

Terminal
/form-utf8       sent: note=%E2%82%B940+%E0%B0%AE%E0%B0%B8%E0%B0%BE%E0%B0%B2%E0%B0%BE  -> decoded: note=₹40 మసాలా
/form-nocharset  sent: note=%26%238377%3B40+%26%233118%3B%26%233128%3B%26%233134%3B%26%233122%3B%26%233134%3B  -> decoded: note=&#8377;40 &#3118;&#3128;&#3134;&#3122;&#3134;

The page without a charset was decoded as Windows-1252 (the Companion to chapter 12, Gaps 2), so the form encoded its data in Windows-1252 too. Characters that don't exist in that encoding (₹ and all of Telugu) can't be represented, and the form specification's fallback replaces each with an HTML numeric character reference (&#8377;), which is then percent-encoded. The server receives &#8377;40 &#3118;…: not an error, just different, silently corrupted text in the database. A missing charset breaks input as well as display (drill D1).

2. "Pressing Enter submits the form": sometimes. The chapter mentions implicit submission. The specification's rule is that Enter in a text field submits if the form has a submit button, or, if it has none, only if it has exactly one field that blocks implicit submission. Real output in Chromium, pressing Enter in the first field of each form:

Terminal
Enter in /one : submitted q=dosa
Enter in /two : nothing submitted

A one-field form without a button submits on Enter (designed for search boxes); a two-field form without a button doesn't. And a form with a submit button submits on Enter from any field, which is how "I pressed Enter in the address field and it placed my order" happens. Every multi-field form should have an explicit submit button, and a form that must not submit on Enter should be a deliberate design, not an accident (drill D2).

3. "type=number gives you a number": it gives you a string, in more forms than you expect. The chapter lists input types. A quantity field with min=1 max=20 step=1, given different typed values (real output):

Terminal
type=number typed '1e1'  : value='1e1'   valid=True  valueAsNumber=10  server got: qty=1e1
type=number typed '-0'   : value='-0'    valid=False valueAsNumber=0  server got: (blocked by validation)
type=number typed '05'   : value='05'    valid=True  valueAsNumber=5  server got: qty=05
type=number typed '2.0'  : value='2.0'   valid=True  valueAsNumber=2  server got: qty=2.0
type=number typed '1.5'  : value='1.5'   valid=False valueAsNumber=1.5  server got: (blocked by validation)
type=number typed ' 3'   : value='3'     valid=True  valueAsNumber=3  server got: qty=3

1e1 (scientific notation), 05 and 2.0 are all valid numbers between 1 and 20 with step 1, so the browser submits them as typed. A server that parses the quantity with [0-9]{1,2} (TiffinBox's stage 9 parser) rejects 1e1 and 2.0; one that uses a general number parser accepts 1e1 as 10. The form's validation and the server's parser disagree about the same field (the Companion to chapter 12's "parser differential" again). Decide the format in one place (the server), and either make the input match it (inputmode="numeric" with pattern="[0-9]{1,2}" on a text input) or normalise on the server (drill D3).

4. "maxlength limits characters": it limits UTF-16 code units. The chapter shows maxlength as a length limit. Typing into a field with maxlength=5 (real output):

Terminal
maxlength=5, typed 'Asha': field kept 'Kalya' (5 UTF-16 units, 5 code points)
maxlength=5, typed '👍👍👍': field kept '👍👍' (4 UTF-16 units, 2 code points)
maxlength=5, typed 'కళ్యాణ్': field kept 'కళ్యా' (5 UTF-16 units, 5 code points)

Two emoji fill four of the five units, so the third doesn't fit. The Telugu name "కళ్యాణ్" (seven code points, three visible syllables) is cut to five code points, removing the final syllable in the middle of a name. maxlength counts UTF-16 code units (the Companion to Volume 1's chapter 6, Code walkthrough on String.length()), which is neither what users perceive as characters nor what a database column measures (often bytes or code points). Set length limits on the server in the unit your storage uses, and keep client limits generous (drill D4).

Common misconceptions

Misconception What's actually true Where it's shown
"Forms always send UTF-8." They send the page's encoding, with &#NNNN; for characters it can't represent. Gaps 1; drill D1
"Enter submits forms." Only with a submit button, or a single field. Gaps 2; drill D2
"type=number sends digits." It sends any valid floating-point string: 1e1, 05, 2.0. Gaps 3; drill D3
"maxlength counts characters." It counts UTF-16 code units; emoji count double, and names can be cut mid-syllable. Gaps 4; drill D4
"A <button> inside a form is just a button." Its default type is submit. Use type="button" for anything else. Explain it differently 4
"ARIA makes elements accessible." ARIA only changes what's announced; it adds no behaviour. Native elements first. Explain it differently 1

Theoretical gaps: the ideas behind the chapter

1. The rule of least power. Tim Berners-Lee's principle: choose the least powerful language suitable for a purpose. HTML is deliberately less powerful than a programming language, and that's its strength: a declarative description of a form can be understood by a browser, a screen reader, a password manager, a search engine and a test tool, while the same form built in JavaScript can only be understood by running it. Every time HTML can express something, expressing it in HTML keeps it analysable and robust (the Companion to chapter 12, theoretical gap 5).

2. HTML is forgiving because the web is written by everyone. The HTML parser never rejects a document: it has defined recovery for every error, so a missing closing tag or a misplaced element still produces a page. That was a deliberate choice (XHTML's strict parsing, where one error showed nothing, lost). The cost is that errors change meaning silently instead of failing loudly. Validators and linters are how authors get back the strictness the parser gave up.

3. Forms are a strict protocol hidden under forgiving markup. Unlike HTML parsing, form submission produces a precise wire format (application/x-www-form-urlencoded, multipart/form-data, text/plain) that servers must parse exactly. The interesting bugs happen where the forgiving side (what users can type, what the page's encoding can represent) meets the strict side (what the server's parser accepts): Gaps 1, 3 and 4 are all at that boundary.

4. Defaults are policy. Default behaviours (a button submits, Enter submits, links open in the same tab, images load eagerly, forms use GET) encode decisions made decades ago for common cases. They're right often enough that relying on them is good practice, and wrong often enough that every default you depend on should be a decision, not an accident. Stating type="button", method="post", loading="lazy" explicitly documents intent for the next reader.

5. Progressive enhancement as an engineering method. Build the HTML version first, working without JavaScript; then enhance it. The method guarantees a baseline (for slow networks, failed script loads, older devices, crawlers and assistive technology), and it forces a clean separation between content and behaviour. It also makes testing easier: the HTML version's behaviour is specified by the platform. The TiffinBox build's stage 13 builds the whole ordering flow this way before any script exists.

6. Accessibility is a property of the whole system, starting from markup. Semantic HTML gives correct roles, names and states for free, and most accessibility failures in real audits are markup failures: missing labels, unlabelled buttons, wrong heading levels, missing alt, clickable divs. Fixing markup is the cheapest accessibility work there is; ARIA and scripting are for what markup genuinely can't express (chapter 20).

Applying it

Code walkthrough

How a browser turns form fields into a request body is specified in the URL standard, and whatwg-url (the JavaScript reference implementation used by jsdom) follows it step by step. Excerpts from whatwg-url 17.3.0, installed from npm.

The form-encoding serializer

lib/urlencoded.js:

JavaScript
// https://url.spec.whatwg.org/#concept-urlencoded-serializer
function serializeUrlencoded(tuples) {
  // TODO: accept and use encoding argument

  let output = "";
  for (const [i, tuple] of tuples.entries()) {
    const name = utf8PercentEncodeString(tuple[0], isURLEncodedPercentEncode, true);
    const value = utf8PercentEncodeString(tuple[1], isURLEncodedPercentEncode, true);

    if (i !== 0) {
      output += "&";
    }
    output += `${name}=${value}`;
  }
  return output;
}

and from lib/percent-encoding.js, the character sets it uses:

JavaScript
// https://url.spec.whatwg.org/#component-percent-encode-set
const extraComponentPercentEncodeSet = new Set([p("$"), p("%"), p("&"), p("+"), p(",")]);
function isComponentPercentEncode(c) {
  return isUserinfoPercentEncode(c) || extraComponentPercentEncodeSet.has(c);
}

// https://url.spec.whatwg.org/#application-x-www-form-urlencoded-percent-encode-set
const extraURLEncodedPercentEncodeSet = new Set([p("!"), p("'"), p("("), p(")"), p("~")]);
function isURLEncodedPercentEncode(c) {
  return isComponentPercentEncode(c) || extraURLEncodedPercentEncodeSet.has(c);
}
JavaScript
function utf8PercentEncodeString(input, percentEncodePredicate, spaceAsPlus = false) {
  let output = "";
  for (const codePoint of input) {
    if (spaceAsPlus && codePoint === " ") {
      output += "+";
    } else {
      output += utf8PercentEncodeCodePointInternal(codePoint, percentEncodePredicate);
    }
  }
  return output;
}

Read it against the chapter and Gaps 1:

  • Each name and value is percent-encoded independently, then joined with = and &. That's why &, = and + in a value must be encoded: they're the format's delimiters.
  • The percent-encode sets nest. The specification defines a chain of sets (C0 controls ⊂ query ⊂ path ⊂ userinfo ⊂ component ⊂ form-urlencoded), each adding characters. Forms use the largest set: everything except ASCII letters, digits and *-._ is encoded. URL paths and queries use smaller sets, which is why the same text can be encoded differently in a URL you type and in a form's body.
  • Spaces become + (spaceAsPlus), a convention only for form encoding. A server that decodes a URL's path with a form decoder turns + into a space, and one that decodes a form with a plain percent-decoder leaves + as a plus: two more ways for components to disagree.
  • "TODO: accept and use encoding argument". The specification's serializer takes the document's encoding, and, for characters that encoding can't represent, substitutes numeric character references, exactly what Chromium did in Gaps 1. This implementation assumes UTF-8, so a form tested in jsdom always produces UTF-8, while the same page in a real browser without a charset produces &#8377;. Tests in a simulated DOM can't catch an encoding bug that only real browsers have.

Read it yourself

  1. A customer's dish note is "1+1 free!". What does the form send, and what would a server that decodes it with a plain URL path decoder store?
  2. Why does the form encoding encode !'()~ when URL queries don't?

Debugging drills

D1. Delivery notes saved as &#3118;&#3128;

The feedback page's notes field stores what customers type. Notes in Telugu and Hindi arrive in the database as sequences like &#3118;&#3128;&#3134;, and "₹" as &#8377;. The page displays correctly for the support team. A reproduction:

Terminal
/form-nocharset  sent: note=%26%238377%3B40+%26%233118%3B%26%233128%3B%26%233134%3B%26%233122%3B%26%233134%3B  -> decoded: note=&#8377;40 &#3118;&#3128;&#3134;&#3122;&#3134;

Explain, fix it, and say what to do about the rows already stored.

D2. "I pressed Enter and it ordered"

The checkout form has address fields and a "Place order" submit button. Customers report that pressing Enter in the address field placed the order before they'd checked the total. A reproduction of the underlying rule:

Terminal
Enter in /one : submitted q=dosa
Enter in /two : nothing submitted

Explain why the checkout form submits on Enter, and propose a fix that's good for keyboard users too.

D3. "Invalid quantity" for a perfectly valid form

The order form uses <input type="number" name="qty" min="1" max="20" step="1">. The server rejects some orders with "quantity must be 1..20". Logs show values like 2.0 and 1e1. A reproduction:

Terminal
type=number typed '1e1'  : value='1e1'   valid=True  valueAsNumber=10  server got: qty=1e1
type=number typed '05'   : value='05'    valid=True  valueAsNumber=5  server got: qty=05
type=number typed '2.0'  : value='2.0'   valid=True  valueAsNumber=2  server got: qty=2.0

Who's wrong, the browser or the server? Fix it.

D4. Names cut in half

The profile form has <input name="displayName" maxlength="20">, and the database column is VARCHAR(20) in a MySQL database using utf8mb4. Some customers with Telugu names see their names cut mid-syllable; one customer with emoji in their name got a server error on save. A reproduction:

Terminal
maxlength=5, typed '👍👍👍': field kept '👍👍' (4 UTF-16 units, 2 code points)
maxlength=5, typed 'కళ్యాణ్': field kept 'కళ్యా' (5 UTF-16 units, 5 code points)

Explain both symptoms, and set the limits properly.

Career-oriented

Interview prep

Mid level

Q1. Build a search box for the TiffinBox menu in HTML only. Which elements and attributes do you use, and what does each give you?

How to get there. Start from the platform: a form with GET (so results have a URL), a labelled input of the right type, the search landmark, and a button. Then name what each piece gives for free (keyboard, accessibility, history, autofill). Interviewers want to see that you know the defaults.

Q2. What's wrong with <div class="btn" onclick="addToCart(12)">Add</div>, and how do you fix it?

How to get there. List what a real button provides that the div doesn't (role, focus, keyboard activation, disabled state, form behaviour), then give the fix and explain why ARIA alone isn't enough.

Senior level

Q3. Your team is about to build the checkout as a React single-page flow. Argue for building it as plain HTML forms first, and say what you'd lose.

How to get there. Make the case with concrete benefits (works without JS, resilience, accessibility, simpler testing), acknowledge real costs (less interactivity, full page loads), and propose the progressive enhancement path. A senior answer is balanced and decides.

Q4. Customers on low-end phones abandon the menu page before it loads. Looking only at the HTML, what would you check and change?

How to get there. Go through what the HTML controls: render-blocking resources, script loading attributes, image dimensions and loading, preloading, and the size of the document itself. Tie each to a measurable effect. Chapter 27 goes deeper; this is the HTML part.

Staff level

Q5. Your organisation has five product teams building forms differently: some native, some with three different component libraries. Accessibility audits keep failing on forms. What's the study plan?

How to get there. Chapter Exercises S3 compares native controls and libraries for one team; this is the organisation. Diagnose the common failures, set one standard (native-first with a small shared kit), make it easy to adopt, and enforce with automated checks.

Q6. Should TiffinBox's public menu pages be optimised for search engines and link previews, and who should own that?

How to get there. Connect HTML decisions (server-rendered content, titles, headings, structured data, Open Graph tags) to business outcomes (discovery, sharing on WhatsApp), and propose ownership and measurement. Chapter Exercises leaves out structured data; this is the decision around it.