Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
JAVASCRIPT FORMS / CHAPTER 05 / Learn / LESSON 01
Forms chapter. A form is the bridge between a person and your code — and a good form starts with a label that is tied to its field.
Theory. <label for="email"> connects to <input id="email"> when the value of for equals the id exactly. Then a click on the text focuses the field, screen readers announce the label, and on phones the touch target is bigger. If for and id differ, the label is just text next to the field.
In JS there are two ways to repair the link: label.setAttribute("for", "email") (or label.htmlFor = "email") and input.id = "email". Both sides are valid — what matters is that they match.
Small examples:
const label = document.querySelector("#l-name"); label.htmlFor = "name"; const field = document.querySelector("#town"); field.id = "city";
Common mistake: changing both sides to different values; forgetting that id must be unique on the page; using name instead of id (name is for FormData, not for for).
<form id="f"><label id="l-name" for="fullname">Name</label><input id="name" name="name" type="text"><label id="l-city" for="city">City</label><input id="town" name="city" type="text"></form>The label for must equal the field id. You fix one side — whichever is wrong.
Press Run — HTML loads in a sandbox iframe; Stop removes the iframe (also kills infinite loops).
›