Forms

Understanding Forms in HTML

HTML forms are an essential part of web development, enabling users to interact with a webpage by entering and submitting data. They provide a structured way to collect input, which can then be processed by a server or a script on the client side. Forms are widely used for various purposes, such as user registration, login pages, search bars, contact forms, feedback collection, and e-commerce checkouts.

When a user submits a form, the data that they entered into the input fields is sent to a specified destination, typically a server-side script that processes and stores the information. Forms rely on various HTML elements, such as text fields, checkboxes, radio buttons, and submit buttons, to collect input efficiently.

HTML Form Structure

Every HTML form is enclosed within <form></form> tags and consists of at least one input field allowing users to enter information. A basic form structure includes:

  • A <form></form> element to define the form.
  • Input fields where the user can input data. These are explored later on this page here.
  • <label></label> elements that quite simply, attach a label to the input field to highlight to the user what they should enter. Think of an “Email:” text to the side of where you enter your email when logging into a website. This can go either before or after their respective input fields depending on whether you want the label to appear to the left or right.
  • A submit button (<button type="submit"><button> or <input type="submit">) to send the form data.

Together these may look like this:

Code

<form action="/submit-form" method="POST">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>

    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>

    <label for="message">Message:</label>
    <textarea id="message" name="message" rows="4"></textarea>

    <button type="submit">Submit</button>
</form>

Result

The attributes for the elements seen above are:

  • <form action="/submit-form" method="POST"></form>
    • action: specifies the URL where form data should be sent after submission. If omitted, the form submits to the current page.
    • method: defines how the form data is transmitted (GET or POST—explained later).
  • <label for="name"></label>
    • for: the value put here will match the id attribute of an input so that we can match up the labels and inputs. In this example this label is for the input with id = "name".
  • <input type="text" id="name" name="name" required>
    • type: the input type attribute lets us specify what type of input is used, for example some text, an email, or a number among lots of others.
    • id: IDs in HTML allow us to pick out a specific element. In forms they let us match that element up with the label. The id here matches the for attribute in the preceding label, assigning the label and input together.
    • name: this attribute is like id, but assigns a unique identifier to the input field so that the form can be processed correctly. When submitted, the data sent to the server is in pairs made up of this name value and the data entered by the user, for example for an email input you would probably want to put the name attribute equal to “email” so that the data the server receives would look like email: example_email@domain.com.
    • required: an attribute preventing the form from submitting without a value entered here. This is a form of form validation which is explored further down the page here.
  • <textarea id="message" name="message" rows="4">
    • The textarea is another input type providing a larger area for the user to type in, useful when you are expecting a long answer such as getting a review from a user or in a complaints form.
    • row: this is a textarea specific attribute detailing how many rows the element will take up in the browser.
  • <button type="submit">
    • type: for HTML buttons their functions can be set via the type attribute. In this case the button will submit the form. HTML buttons are explored more here.

GET and POST

The method attribute in the <form> element determines how the form data is sent to the server. There are two main options: GET and POST.

A GET method sends form data as query parameters in the URL (e.g., example.com/search?q=HTML+Forms) which is best used for search forms, filters, or retrieving data. As these appear in the URL, they can be bookmarked and shared easily and are cached by browsers, improving performance. However don't use them for passwords or sensitive data, so as to prevent these from being exposed in the URL.

A POST method sends form data in the request body, making it invisible in the URL. It is commonly used for login forms, registration, payments, and contact forms. It is more secure than GET as the data is not stored in browser history and can handle large amounts of data. However it cannot be bookmarked or cached by browsers.

Common Form Elements

To build an effective form, it is important to use the right input elements, and the are many to choose from in HTML. A full list of them can be found here.

Most of them exist as different values that you can assign to the type attribute of the <input> element. Please note that the input element is self closing. Listed here are a few useful ones with examples:

Text Input

Used for entering short text values, it provides a text input field, accepts letters, numbers, special characters.

Code

<input type="text" name="username">

Result

Password Field

Hides characters entered by the user by replacing any entered characters with *.

Code

<input type="password" name="password">

Result

Email Input

Automatically validates email format to check that the entered value at least looks like a valid email address.

Code

<input type="email" name="email">

Result

Search Input

Similar to text input but has an X that comes up when a query is entered. This X clears the entered data (as does pressing esc).

Code

<input type="search" name="search">

Result

Number Input

For number inputs, with an up/down arrow to help users pick a value. Use the min and max attributes to define the minimum and maximum values respectively.

Code

<input type="number" name="quantity" min="1" max="5">

Result

Range Input

A slider that can be controlled with arrow keys, also uses the min and max attributes.

Code

<input type="range" name="points" min="0" max="10">

Result

Radio Buttons

Allows users to select one option from multiple choices. The radio group is defined by giving each of the buttons the same name attribute.

Code

<input type="radio" name="subscribe" value="yes"> Yes
<input type="radio" name="subscribe" value="no"> No

Result

Yes No

Check Boxes

Lets users select one or multiple options. The value attribute dictates what is sent to the server in the value: input pair. To have an option pre-checked, add the checked attribute.

Code

<input type="checkbox" name="age" value="1-10"> 1-10
<input type="checkbox" name="age" value="10-18"> 10-18
<input type="checkbox" name="age" value="18+" checked> 18+

Result

1-10 10-18 18+

Date Selector

Creates an input field that shows a date-picker when clicked.

Code

<label for="birthday">Birthday:</label>
<input type="date" id="birthday" name="birthday">

Result

Select

Select is its own element rather than a value for the type attribute of an input element and has a closing tag associated with it. Within the element, there are option elements for each choice available to the user. Select creates a drop-down menu for the user to pick an option from. Add the selected attribute to have that option selected by default.

Code

<select name="country">
    <option value="us" selected>United States</option>
    <option value="uk">United Kingdom</option>
</select>

Result

Textarea

Textarea is also its own element rather than a value for the type attribute of an input element and has a closing tag associated with it. It gives the user an area to enter more text. It can have attributes of rows and cols to format the height and width respectively and you can give the placeholder attribute a value to fill it with placeholder text or prepopulate it with text by typing it between the <textarea></textarea> tags.

Code

<textarea name="placeholder" rows="4" cols="30" placeholder="placeholder text"<
</textarea<
<textarea name="prepopulated" rows="4" cols="30"<
Prepopulated with text
</textarea<

Result

Form Validation

Forms should validate user input to ensure data is correct before submission. HTML provides some built-in validation using attributes like required, minlength, maxlength, and pattern.

<input type="text" name="username" required minlength="3" maxlength="15">
<input type="email" name="email" required>
<input type="password" name="password" required pattern=".{6,}">
  • required: ensures the field is not empty.
  • minlength & maxlength: sets character limits.
  • pattern: uses regex to enforce specific formats.