Forms, Labels and Buttons
What Is It?
A form collects answers. A label tells the reader what to enter, and a button starts an action.
What the Tags Mean
form: groups fields.label: names a field.input: a place to type.forandid: connect the label to the input.name: names the answer when it is sent.button: a clickable control.
Example 1
Save each example as index.html and open it in your browser. Each code block is a complete page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Forms, Labels and Buttons</title>
</head>
<body>
<form>
<label for="name">Your name</label>
<input id="name" name="name" type="text">
<button type="button">Continue</button>
</form>
<pre id="result" role="status">Your answers will appear here. Nothing is sent or saved.</pre>
<script>
document.querySelectorAll("form").forEach((form) => {
form.addEventListener("submit", (event) => {
event.preventDefault();
const answers = [];
for (const [name, value] of new FormData(form)) {
answers.push(name + ": " + (value instanceof File ? value.name : value));
}
document.getElementById("result").textContent = answers.join("\n") || "No answers entered.";
});
});
document.querySelectorAll("button[type=button]").forEach((button) => {
button.addEventListener("click", () => {
button.closest("form").requestSubmit();
});
});
</script>
</body>
</html>Browser preview
What you see: Type a name and press Continue. A short script shows your answer below the form. Nothing is sent or saved.
Example 2: Another Use
Use required and a submit button when the browser should check an answer.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Forms, Labels and Buttons</title>
</head>
<body>
<form>
<label for="email">Email</label>
<input id="email" name="email" type="email" required>
<button type="submit">Check</button>
</form>
<pre id="result" role="status">Your answers will appear here. Nothing is sent or saved.</pre>
<script>
document.querySelectorAll("form").forEach((form) => {
form.addEventListener("submit", (event) => {
event.preventDefault();
const answers = [];
for (const [name, value] of new FormData(form)) {
answers.push(name + ": " + (value instanceof File ? value.name : value));
}
document.getElementById("result").textContent = answers.join("\n") || "No answers entered.";
});
});
document.querySelectorAll("button[type=button]").forEach((button) => {
button.addEventListener("click", () => {
button.closest("form").requestSubmit();
});
});
</script>
</body>
</html>Browser preview
Simple Tip
An empty or invalid email blocks submission. A valid answer appears below the form. This local demonstration does not register anyone.
Try It Yourself
Click the Name label. Does the cursor move into the field?