HTML Forms: form, label, input and button Basics
Forms are how a page collects input: a search box, a sign-up, a checkout. The browser does a lot of work for you, including keyboard handling, validation, autofill and submission, as long as you use the right elements.
The form element
<form> wraps the controls. Its action is the URL that receives the data, and method is how it is sent:
method="get"puts the data in the URL, as in/search?q=for+loop. Use it for searches and filters, since the result can be bookmarked and shared.method="post"sends the data in the request body. Use it for anything that changes data on the server, such as creating an account.
Each control needs a name attribute; that becomes the key in the submitted data. A field without a name is not submitted at all.
Labels
Every input needs a <label>. Connect them either with for matching the input's id, as in the search form, or by wrapping the input inside the label, as in the sign-up form. A connected label is read aloud by screen readers, and clicking it focuses the field or toggles the checkbox, which makes small controls much easier to hit. A placeholder is not a label: it disappears as soon as you type.
Expected page text
Search lessons Search Email Weekly digest Subscribe
Buttons and submission
A <button> inside a form submits it by default, because its default type is submit. Write type="button" for buttons that run JavaScript and should not submit. Pressing Enter in a text field also submits the form.
Before submitting, the browser checks built-in rules such as required and type="email", and shows a message if a field is invalid. This is a convenience for users, not security: always validate again on the server.
Handling a form with JavaScript
The script in the example listens for the submit event, calls preventDefault() to stop the page from navigating, and reads the values with FormData. In the preview, type an email address and press Subscribe to see the result in the console. A checked checkbox submits the value "on" unless you give it a value attribute.
Common mistakes
- Inputs without labels, or with only a placeholder.
- Forgetting
name, so the field's value is never sent. - Using
method="get"for passwords or other sensitive data, which ends up in browser history and server logs.
Summary
<form action method>wraps controls;getfor searches,postfor changes.- Every control needs a
nameand a connected<label>. - Buttons submit by default; use
type="button"for other actions. - Browser validation helps users, but the server must still validate.
Quiz: Forms