Skip to main content

Form Basics

Resource

I. Form Elements

1. form element

The <form> element is a container element that wraps all inputs a user will interact with on a form. The form element can accept two essential attributes :

  • action attribute takes a URL value, telling the form where it should send its data to be processed.
  • method attribute tells the browser which HTTP request method to submit the form. e.g. GET, POST.
<form action="example.com/path" method="post"></form>

To start collecting user data, we need to use form control elements. These are all the elements users will interact with on the form, such as text boxes, dropdowns, checkboxes, and buttons. In the following few sections, we will explore some of the form controls you will use most commonly.

2. input element

The input element accepts a type attribute, which tells the browser what type of data it should expect and how it should render the input element.

<form action="example.com/path" method="post">
<input type="text">
</form>

The <input> element can have various types specified through the type attribute. Commonly used types are:

  1. text: This is the default type if no type attribute is specified. It creates a single-line text input field for users to enter text.

  2. password: This type creates a single-line text input field where the characters entered are masked (e.g., displayed as dots or asterisks) for security purposes, typically used for password inputs.

    <label for="user_password">Password:</label>
    <input type="password" id="user_password" name="password">
  3. email: This type creates a single-line text input field specifically for entering email addresses. Some browsers may apply additional validation or formatting for email inputs.

    <label for="user_email">Email Address:</label>
    <input type="email" id="user_email" name="email" placeholder="you@example.com">
  4. number: This type creates a single-line text input field that accepts only numerical values. Browsers may provide up/down arrows or a number picker for easy value selection.

    <label for="amount">Amount:</label>
    <input type="number" id="amount" name="amount">
  5. checkbox: This type creates a checkbox input that can be toggled on or off.

  6. radio: This type creates a radio button input that allows selecting one option from a group of related options.

  7. file: This type creates a file input field that allows users to select one or more files from their local file system for uploading.

  8. date: This type creates an input field specifically for entering a date. Browsers may provide a date picker or calendar for easy date selection.

    <label for="dob">Date of Birth:</label>
    <input type="date" id="dob" name="dob">
  9. time: This type creates an input field specifically for entering a time value.

  10. submit: This type creates a submit button that, when clicked, submits the form data to the server specified in the action attribute.

  11. hidden: This type creates an invisible input field that can be used to store data that should be submitted with the form but not visible to the user.

  12. search: This type creates a single-line text input field for entering search queries. Browsers may provide specific styling or functionality for search inputs.

3. label element

We can give labels to our inputs using the <label> element to inform users what type of data they are expected to enter.

<form action="example.com/path" method="post">
<label for="first_name">First Name:</label>
<input type="text" id="first_name">
</form>

Labels accept a for attribute, which associates it with a particular input. The input we want to associate with a label needs an id attribute with the same value as the label’s for attribute. → When a label is associated with an input and is clicked, it will focus the cursor on that input, ready for the user to input some data.

4. textarea element

While technically not an input element, the <textarea> element provides an input box that can accept text that spans multiple lines like user comments and reviews. It can also be resized by clicking and dragging the bottom right corner to make it bigger or smaller.

Text area elements accept a couple of unique attributes that other form controls do not such as the rows and cols attributes. They allow you to control the initial height (rows) and width (cols) of the text area:

<textarea rows="20" cols="60">Some initial content.</textarea>

II. Form Attributes

1. placeholder attribute

To guide users on what to enter in form elements, we can add a placeholder attribute to an input. The value will be the placeholder text we want to display in the input:

<label for="first_name">First Name:</label>
<input type="text" id="first_name" placeholder="Bob...">

2. name attribute

The name attribute is a crucial part of form input fields as it serves as an identifier for the data being submitted from that particular input field.

When a form is submitted, the browser collects the values from each input field and sends them to the server as key-value pairs. The name attribute is used as the key, and the value entered or selected in the input field becomes the corresponding value.

Consider the following HTML code:

<form action="https://httpbin.org/post" method="post">
<div>
<label for="first_name">First Name:</label>
<input type="text" name="first_name" id="first_name">
</div>

<div>
<label for="last_name">Last Name:</label>
<input type="text" name="last_name" id="last_name">
</div>

<div>
<label for="age">Age:</label>
<input type="number" name="age" id="age">
</div>

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

When this form is submitted, the data submitted to the server might look something like this:

first_name=John&last_name=Doe&age=30
  • If an input field doesn't have a name attribute, its value will not be included in the submitted form data.
  • The name attribute should be unique within a form to avoid conflicts when processing the data on the server side.

Using form controls outside of form

You can use any HTML form controls outside the <form> element. For instance, you might want to use an input field to collect data from a user and then display that data elsewhere on the page using JavaScript.

<!-- the form controls aren't nested inside <form> tag -->
<div>
<label for="username">What's your name?</label>
<input type="text"id="username">
<button class="greet-btn">Greet Me</button>
</div>

<h1 class="greeting"></h1>
const name = document.querySelector("#username")
const greetMeButton = document.querySelector(".greet-btn")
const greetingOutput = document.querySelector(".greeting")

greetMeButton.addEventListener('click', (event) => {
greetingOutput.innerText = `Hello ${name.value}`;
})

III. Selection Elements

Sometimes you will want users to select a value from a predefined list. This is where select elements will be useful.

1. Select dropdown

The <select> element creates a dropdown list of options the user can choose from. Each option is defined using the <option> element nested inside the <select> element.

  • Each <option> element should have a value attribute representing the value submitted to the server when that option is selected.
<select name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
</select>

1. Setting a default selected option

By adding the selected attribute to an <option> element, that option will be pre-selected when the page loads.

<select name="country">
<option value="usa">USA</option>
<option value="canada" selected>Canada</option>
<option value="mexico">Mexico</option>
</select>

2. Grouping options - <optgroup>

The <optgroup> element allows you to group related options under a label, making it easier for users to navigate and understand the available choices.

<select name="vehicle">
<optgroup label="Cars">
<option value="honda">Honda</option>
<option value="toyota">Toyota</option>
</optgroup>
<optgroup label="Motorcycles">
<option value="ducati">Ducati</option>
<option value="harley">Harley-Davidson</option>
</optgroup>
</select>

3. Multiple selections

By adding the multiple attribute to the <select> element, users can select more than one option by holding down the Ctrl (or Command on Mac) key while clicking on the desired options.

<select name="toppings" multiple>
<option value="cheese">Cheese</option>
<option value="pepperoni">Pepperoni</option>
<option value="mushrooms">Mushrooms</option>
<option value="onions">Onions</option>
</select>

2. Radio buttons

To create radio buttons, we use <input> element with a type attribute of “radio”. Radio buttons allow us to create multiple options so that the user can choose one.

<h1>Ticket Type</h1>
<div>
<input type="radio" id="child" name="ticket_type" value="child">
<label for="child">Child</label>
</div>

<div>
<input type="radio" id="adult" name="ticket_type" value="adult">
<label for="adult">Adult</label>
</div>

<div>
<input type="radio" id="senior" name="ticket_type" value="senior">
<label for="senior">Senior</label>
</div>

When we select one of the radio buttons and then select another, it will deselect the first one. Radio buttons know to do this because they have the same name attribute. This is how the browser knows these elements are part of the same group of options.

We can set the default selected radio button by adding the checked attribute to it:

<h1>Ticket Type</h1>
<div>
<input type="radio" id="child" name="ticket_type" value="child">
<label for="child">Child</label>
</div>

<div>
<input type="radio" id="adult" name="ticket_type" value="adult" checked>
<label for="adult">Adult</label>
</div>

<div>
<input type="radio" id="senior" name="ticket_type" value="senior">
<label for="senior">Senior</label>
</div>

3. Checkboxes

Checkboxes are similar to radio buttons in that they allow users to choose from a set of predefined options. But unlike radio buttons, they allow multiple options to be selected at once. To create a checkbox, we use the <input> element with a type attribute of “checkbox”.

<h1>Pizza Toppings</h1>

<div>
<input type="checkbox" id="sausage" name="topping" value="sausage">
<label for="sausage">Sausage</label>
</div>

<div>
<input type="checkbox" id="onions" name="topping" value="onions">
<label for="onions">Onions</label>
</div>

<div>
<input type="checkbox" id="pepperoni" name="topping" value="pepperoni">
<label for="pepperoni">Pepperoni</label>
</div>

<div>
<input type="checkbox" id="mushrooms" name="topping" value="mushrooms">
<label for="mushrooms">Mushrooms</label>
</div>

We can also have a single checkbox when we want users to toggle if they want something to be true or false. Like signing up for a newsletter when they create an account for example:

<div>
<input type="checkbox" id="newsletter" name="news_letter">
<label for="newsletter">Send me the news letter</label>
</div>

We can set checkboxes to be checked by default on page load by giving them a checked attribute:

<div>
<input type="checkbox" id="newsletter" name="news_letter" checked>
<label for="newsletter">Send me the news letter</label>
</div>

IV. Buttons

The <button> element creates clickable buttons that the user can interact with to submit forms and trigger other actions. The content or text we want to have displayed inside the button will go within the opening and closing tags:

<button>Click Me</button>

The button element also accepts a type attribute that tells the browser which kind of button it is dealing with. There are three types of buttons available.

1. Submit button

Yes, that's correct. When you include a <button> element with type="submit" inside a <form> element, it creates a submit button that, when clicked, will submit the form data to the server specified in the action attribute of the <form> element.

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

If the type attribute is omitted, the default value is "submit", so you can also create a submit button like this: <button>Submit</button>.

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

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

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

2. Reset button

The <button> element with type="reset" creates a reset button within an HTML form. When clicked, this button will reset all form fields to their initial or default values, clearing any user input.

<button type="reset">Reset</button>
<form>
<label for="name">Name:</label>
<input type="text" id="name" name="name">

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

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

3. Generic button

Unlike the submit and reset buttons, the <button> element with type="button" creates a generic button with no default associated behavior.

<button type="button">Click to Toggle</button>

V. Organizing form elements

Resource

1. fieldset element

<fieldset> is a container element used to group related form controls together, creating a logical section or category within a larger form. By grouping related inputs within a <fieldset>, you can create a more structured and organized layout for your form.

<fieldset>
<label for="first_name">First Name</label>
<input type="text" id="first_name" name="first_name">

<label for="last_name">Last Name</label>
<input type="text" id="last_name" name="last_name">
</fieldset>

2. legend element

The <legend> element is used in conjunction with the <fieldset> element to provide a caption or heading for the group of form controls. It helps users understand the purpose or context of the grouped form elements.

The <legend> element should be placed immediately after the opening <fieldset> tag, and it will be rendered as a visible label or title for that section of the form.

<fieldset>
<legend>Contact Details</legend>

<label for="name">Name:</label>
<input type="text" id="name" name="name">

<label for="phone_number">Phone Number:</label>
<input type="tel" id="phone_number" name="phone_number">

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

<fieldset>
<legend>Delivery Details</legend>

<label for="street_address">Street Address:</label>
<input type="text" id="street_address" name="street_address">

<label for="city">City:</label>
<input type="text" id="city" name="city">

<label for="zip_code">Zip Code:</label>
<input type="text" id="zip_code" name="zip_code">
</fieldset>

VI. Form Validation

Resources

We use form validation to enforce rules and constraints on user input and ensure that the data entered meets certain criteria. When a user enters invalid data that doesn't conform to the specified rules, validation messages or feedback can be displayed, guiding the user to correct the input before submitting the form.

1. Required validation

The required attribute makes a form field mandatory, meaning the user must provide a value before submitting the form. This validation ensures crucial information is not missing when the form is submitted.

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

It's important to indicate which fields are required, often done by adding an asterisk * or other visual cue to the field label.

2. Text length validations

1. Minimum length validation

To add the minimum length validation, we give the form control a minlength attribute with an integer value representing the minimum number of characters we want to allow in the form control.

<textarea minlength="3"></textarea>

2. Maximum length validation

To add a maximum length validation, we give the form control a maxlength attribute with an integer value representing the maximum number of characters we want to allow in the form control.

<textarea placeholder="What's happening?" maxlength="20"></textarea>

3. Number range validations

1. min validation

To add a minimum value validation, we give the form control a min attribute with an integer value representing the minimum number we want the form control to accept:

<input type="number" id="quantity" name="quantity" min="1" value="0">

2. max validation

To add a maximum value validation, we give the form control a max attribute with an integer value representing the maximum number we want the form control to accept.

<input type="number" id="passengers" name="passengers" max="5" value="0">

4. Pattern validations

To add a pattern validation, we give the form control a pattern attribute with a regular expression as the value. The pattern attribute can only be used on <input> elements.

In the example, we are using the pattern validation to ensure a US zip code is in the correct format (5 numbers followed by an optional dash and 4 more numbers):

<!-- example -->
<input type="text" id="zip_code" name="zip_code" pattern="(\d{5}([\-]\d{4})?)" placeholder="e.g. 12345-6789">

4. Styling validations

We can target form controls that have passed or failed validations using the :valid and :invalid pseudo-classes.

For example, we target any valid inputs and give them a green border, and when a field is invalid, we give it a red border instead.

input:invalid {
border-color: red;
}

input:valid {
border-color: green;
}