DEV Community

Richard Pascoe
Richard Pascoe

Posted on

How Do Forms, Labels, and Inputs Work in HTML?

After reviewing semantic HTML elements on freeCodeCamp this morning and passing the quiz, I started a new series of theory lessons on working with forms this afternoon. This post covers the first lesson in that series.

The form element in HTML is used to gather information that the user has input, as shown in the following example:

<form action="url-goes-here">
  <!-- input elements go here -->
</form>
Enter fullscreen mode Exit fullscreen mode

The action attribute defines the destination where form data is sent when the form is submitted. To gather specific details - such as names or email addresses - you use the input element.

Input elements are void elements, meaning they do not require closing tags. The type attribute defines the type of data expected from the user; in this example, the data is plain text. To describe the input field, you use a label element. Below is an example of a label element with its associated text:

<form action="">
  <label>
    Full Name:
    <input type="text" />
  </label>
</form>
Enter fullscreen mode Exit fullscreen mode

By nesting an input element inside a label element, you create an implicit association between the label and the input field. Implicit means the relationship is understood without being directly specified through additional attributes or elements. To explicitly link a label to an input, you can use the for attribute. The following example shows how to use the for attribute with an email address label:

<form action="">
  <label for="email"> Email Address: </label>
  <input type="email" id="email" />
</form>
Enter fullscreen mode Exit fullscreen mode

When creating an explicit association between a label and an input, the for attribute on the label and the id on the input must have the same value. In this example, both are set to email. Setting the input type to email provides basic validation to ensure the address is correctly formatted. To give users additional guidance on the expected input, you can use the placeholder attribute. The following example demonstrates using a placeholder inside an email input:

<form action="">
  <label for="email"> Email Address: </label>
  <input type="email" id="email" placeholder="example@email.com" />
</form>
Enter fullscreen mode Exit fullscreen mode

Placeholder text should provide brief, helpful guidance that indicates the format and type of data expected from the user. In this case, the placeholder text shows the user that a correctly formatted email address is required.

There are three more theory lessons on working with forms, though I won’t be covering them here. The next post in this Learning with freeCodeCamp series will be a hands-on workshop: building a hotel feedback form. Stay tuned to see how it all comes together!

Written by a Human logo

Top comments (0)