HTML and CSS

Lesson 8 of 10

Lesson ยท 10 min

Forms

What a form is

A form collects information from the reader. It holds controls such as text boxes, menus, and buttons. When the reader clicks the submit button, the browser sends the values to a server.

The preview does not send data. It only shows how the form looks and checks your HTML.

Labels and inputs

Every control needs a label. A label tells the reader what to type. It also helps screen readers, and it makes the control easier to click, because a click on the label moves the cursor into the field.

You connect them with two matching values:

<label for="city">City</label>
<input type="text" id="city" name="city">
  • for on the label and id on the input must be the same.
  • name is the name that the server receives with the value.

The type attribute changes what the input accepts. Common types are text, email, password, number, and checkbox. An email input shows a keyboard made for email on a phone, and the browser can check the value.

The required attribute stops the browser from sending the form while the field is empty.

Menus

A select element shows a menu. Each choice is an option.

<select id="size">
  <option>Small</option>
  <option>Large</option>
</select>

Buttons

A button with type="submit" sends the form. The text between the tags is the text on the button.

Your turn

Build the form in four steps. Press Run after each step to see the form grow.

Tasks

4 to do

  1. Task 1, not checked yet. Add a form element. Inside it, add a label with the text Email and an input with type="email". Connect them: give the input id="email" and give the label for="email".

  2. Task 2, not checked yet. Make the email input required, and give it the name email. Add the required attribute and name="email".

  3. Task 3, not checked yet. Add a second field: a label with the text Topic and a select element with id="topic". The select has two option elements: News and Tips. The label must have for="topic".

  4. Task 4, not checked yet. Add a button with the text Subscribe and type="submit", inside the form.

Task 1 of 4

Add a form element. Inside it, add a label with the text Email and an input with type="email". Connect them: give the input id="email" and give the label for="email".

All tasks

index.html

Ctrl+Enter runs your code. Ctrl+Shift+Enter checks it. Press Esc, then Tab, to leave the editor.

Preview

Your page shows here