Forms

Forms are a part of everyday life. It is almost impossible to avoid them when doing some kind of paperwork, registration or sending an application.

Just like the form that we fill our information, an HTML <form> element is designed to collect information to send somewhere else. Often when you are filling a text field on a webpage it is probably part of a  <form> tag.

In this lesson, we’ll go over the structure and syntax of a <form> and the many elements that populate it.

How a Form Works

The internet is a network of computers which send and receive information. Computers use HTTP requests to exchange data. The HTTP request instructs the receiving computer how to handle the incoming information.

The <form> element is a perfect tool for collecting information, but then the gathered information needs to be sent somewhere else like a server to be processed. If we want to specify where the HTTP request should go and what method should be used, we need to assign values to action and method attributes on the form <form> element. Take a look at the example below:

<form action=“/somewhere.html” method=POST>
</form>

 

  • The action attribute determines where the information should be sent. (somewhere.html in this example)
  • The method attribute will be assigned a HTTP verb or method. (POST request in this example)

You will get familiar with HTTP verbs in the future.

There are different other elements that can be used as children of <form> element.  The following example shows the usage of elements like <h1> and <div> which you are already familiar with.  

<form action=“/example.html” method=POST>
  <h1>Registration Form</h1>
  <div>If you are willing to register for the HTML course, please fill the    following form.</div>
</form>

 

As we mentioned earlier, the main purpose of placing a <form> element on our web page is to collect user information but the above example does not do so! Let’s go ahead and learn some other elements that would make our form more interactive.

Text Input

Suppose we want to have an input field on the form to get the user’s first and last name. This is done using an <input> element. The <input> element has a type attribute which determines how it renders on the web page and what kind of data it can accept.

The values that can be set for the type attribute are listed below: 

  • text
  • password
  • number
  • range
  • checkbox
  • radio

We will discuss each one of these types and how they are used.

The first value for the type attribute we’re going to explore is “text”. When we create an <input> element with type=”text”, it renders a text field that users can type into. The <input> element also has a name attribute which is required if we want the information inside the element to be sent to the server when the form is submitted.

The following example results in an input field on the screen:

<form action=“/example.html” method=POST>
  <input type=“text” name=“text-field”>
</form>

 

The <input> element has also got an attribute called value. Whenever the user types something inside the text field, it is automatically assigned to the value attribute.

The value of the value attribute is paired with the value of the name attribute and sent as text when the form is submitted. For example, If a user type “Learning HTML” inside the text field:

When the form is submitted, the text: “text-field=Learning HTML” is sent to /example.html because the value of the name attribute is “text-field” and the value of value is “Learning HTML”.

It is also possible to set a default value for the text filled so that it has some value the first time it is shown to the user. This is done using the  value attribute: 

<form action=“/example.html” method=POST>
  <input type=“text” name=“text-field” value=“default value”>
</form>

 

The result would be as following the first time the page is shown :

Adding a Label

Often times when you decide to add a text field to a form. You need to provide some information about what needs to be typed inside the <input> element. That can be achieved by  <label> element. The <label> element has an opening and closing tag and displays text that is written between the opening and closing tags. To associate a <label> and an <input>, the <input> needs an id attribute. We then assign the for attribute of the <label>element with the value of the id attribute of <input>, like so:

<form action=“/example.html” method=POST>
  <label for=“name-field”>Name</label>
  <br>
  <input type=“text” name=“Name” id=“name-field”>  <label for=“id-field”>ID</label>
  <br>
  <input type=“text” name=“ID” id=“id-field”>
</form>

 

The code above renders:

Another benefit for using the <label> element is when this element is clicked, the corresponding <input> is highlighted/selected.

Password Input

You most probably have encountered forms on the internet that require you to enter a password. It is essential for a password field to hide it’s content from other people to read it. Luckily,there is a  type=”password” attribute for <input> element!

An <input type =”password”> element will replace input text with another character like a star (*) or a dot (•). Password fields are created like this?

<form>
  <label for=“user-password”Password: </label>
  <input type=“password” id=“user-password” name=“user-password”>
</form>

 

After a user types into the field, it would look like:

Even though the password field makes the text of the password invisible to the eyes, when the form is submitted, the value of the text is still sent to the server.

Number Input

Another type of input we most probably need to get from users is a number! type=”number” would just do that for us like the following:

<form>
  <label for=“age”>Age: </label>
  <input id=“age” name=“age” type=“number” step=“1”>
</form>

 

Which renders:

By setting type=”number” for an <input> we can restrict what users type into the input field to just numbers (and a few special characters like , +, and .). You might notice in the example there is also a step attribute set to 1. This will provide arrows inside the <input> field to set the number inside. When the value of the  step attribute is  set to 1, every time you press the arrows, it will increase or decrease the number by one.

Range Input

Setting the type=”range” will create a slider for us on the screen. This can be useful when we want to give the user a range of numbers to select from like a volume control.

To set the minimum and maximum values of the slider we assign values to the min and max attribute of the <input>. Also the step attribute determines how the value of the field changes every time the handle is moved by the user. Below is an example of how this type works:

<form>
  <label for=“volume”> Volume Control</label>
  <input id=“volume” name=“volume” type=“range” min=“1” max=“1000” step=“1”>
</form>

 

The above example renders to:

In the example above, every time the slider moves by one, the value of the <input>‘s value attribute changes.

Checkbox Input

So far we have learned how to get single choice values from the user. However, there are cases where user needs to choose between different options provided. That’s where checkbo’s come in handy! By setting type=”checkbox” of the <input> element, we have created a checkbox. In the following example you can see multiple checkboxes separated by <br> tags: 

<form>
  <p>Choose your meal:</p>
  <label for=“green-salad”>Green Salad</label>
  <input id=“green-salad” name=“meal” type=“checkbox” value=“green-salad”>
  <br>
  <label for=“pizza”>Pizza</label>
  <input id=“pizza” name=“meal” type=“checkbox” value=“pizza”>
  <br>
  <label for=“french-fries”>French Fries</label>
  <input id=“french-fries” name=“meal” type=“checkbox” value=“french-fries”>  <br>
  <label for=“pasta”>Pasta</label>
  <input id=“pasta” name=“meal” type=“checkbox” value=“pasta”>
</form>

 

Which renders:

There are a few points worth mentioning about checkboxes:

  • The values assigned to the value attribute of checkboxes are not gonna be shown on the page, therefore, we need to put labels containing values alongside them.
  • Using the same name attribute for all of our checkboxes groups them together, yet each one of them is identifiable using their own unique id.

Radio Button Input

Checkboxes are useful when you need to give the user the opportunity to choose multiple options at the same time. But there are cases when you need to force the user to choose only one from the list. In these cases, we take advantage of radio buttons.

Here’s an example of how radio buttons are created:

<form>
  <p>Choose your gender:</p>
  <input type=“radio” id=“male” name=“gender” value=“male”>
  <label for=“male”>Male</label>
  <br>
  <input type=“radio” id=“female” name=“gender” value=“female”>
  <label for=“female”>Female</label>
</form>

 

Which renders:

Notice from the code snippet, radio buttons (like checkboxes) do not display their value. We have an associated <label> to represent the value of the radio button. To group radio buttons together, we assign them the same name and only one radio button from that group can be selected.

Dropdown list

Sometimes the number of options you want to present to the user is a lot. Dropdown lists are a great option for these cases.

Here’s an example of how to create a dropdown list:

<form>
  <label for=“course”>Choose your favorite course:</label>
  <select id=“course” name=“course”>
    <option value=“html”>HTML</option>
    <option value=“css”>CSS</option>
    <option value=“javascript”>JavaScript</option>
    <option value=“bootstrap”>Bootstrap</option>
    <option value=“react”>React</option>    <option value=“git”>Git</option>
  </select>
</form>

 

Which renders:

 

And if we click on the field containing the first option, the list will be shown:

Notice in the code we used <select> element to create the dropdown list itself and <option> element to add items to the list. Each of these items have a value attribute. Only one of these options can be selected.

The text rendered is the text included between the opening and closing <option>tags. However, it is the value of the value attribute that is used in <form> submission (notice the difference in the text and value capitalization). When the <form> is submitted, the information from this input field will be sent using the name of the <select> and the value of the chosen <option>. For instance, if a user selected JavaScript from the dropdown list, the information would be sent as “course=JavaScript”.

Datalist Input

In previous section, We learned how to let users select from a list of options using dropdown lists. These lists are created using  <select> and <option> elements. But imagine the number of options become too many. Then it would be tiresome for the user to find their desired option just by scrolling.

 

Using the <datalist> element with an <input type=”text”> will create a text field that filters the data as the user types in it. It is kind of like a search box. Let’s look at an actual example:

<form>
  <label for=“city”>Select your desired course:</label>
  <input type=“text” list=“courses” id=“course” name=“course”>

  <datalist id=“courses”>
    <option value=“HTML”></option>
    <option value=“CSS”></option>
    <option value=“JavaScript”></option>
    <option value=“Git”></option>
    <option value=“Bootstrap”></option>
    <option value=“React”></option>    <option value=“Node and Express”></option    <option value=“MongoDB”></option    <option value=“TDD Javascript”></option>
  </datalist>
</form>

 

Notice, in the code above, we have an <input> that has a list attribute. The <input> is associated to the <datalist> via the <input>‘s list attribute and the id of the <datalist>.

From the example above the following form is rendered:

And when field is selected:

While <select> and <datalist> share some similarities, there are some major differences. In the associated <input> element, users can type in the input field to search for a particular option. If none of the <option>s match, the user can still use what they typed in. When the form is submitted, the value of the <input>‘s name and the value of the option selected, or what the user typed in, is sent as a pair.

Textarea element

An <input> element with type=”text”creates a single row input field for users to type in information. However, there are cases where users need to write in longer blocks of code like a message. In such cases, instead of using an <input>, we could use <textarea>.

The <textarea> element is used to create a bigger text field for users to write more text. We can add the attributes rows and cols to determine the amount of rows and columns for the <textarea>. Look at the following example:

<form>
  <label for=“message”>Your message: </label>
  <br>
  <textarea id=“message” name=“message” rows=“10” cols=“40”>
  </textarea>
</form>

 

In the code above, an empty <textarea> element with 10 rows and 40 columns is rendered to the page like this:

The two small lines you see on the bottom right corner are for expanding the textarea even more if the user needs more space.

When we submit the form, the value of <textarea> is the text written inside the box. If you type something between the opening and closing tags, that would be rendered as the textarea’s default value like this:

<textarea>This is where you type your message</textarea>

 

This will result in a <textarea> that contains default text: “This is where you type your message”.

Submit Form

If you remember, at the beginning of the form section of this book, we stated that the main purpose of placing a form on our webpage is to collect information from the user. Now let’s go ahead and submit that information and send it.

In order to achieve this we need a submit button for our form! A submit button is simply created by a <input> element and setting the type to “submit”. Let’s have a look at how it’s done: 

<form>
  <input type=“submit” value=“Send the Info!”>
</form>

 

Which renders:

Notice in the code snippet that the value assigned to the <input> shows up as text on the submit button. If there isn’t a value attribute, the default text, Submit shows up on the button.

Form Validation

Validation is the concept of checking user provided data against the required data. It is the process that happens when you want to log into a website or submit an online application.

There are different types of validation. One type is server-side validation, this happens when data is sent to a server for validation. An example of this type of validation is the usage of a login page. The form on the login page accepts username and password input, then sends the data to a server which checks that the pair matches up correctly. However, some types of validation don’t need to happen at the server-side. Like when you want to force the user to fill a specific input field and not leave it empty or check the length of an input text.

Requiring an Input

In some cases there are fields on our <form> that are not optional. To force the user to fill that field, we can add the required attribute to an <input> element. For example:

<form action=“/example.html” method=“POST”>
  <label for=“medication”>Are you under any kind of medication?</label>
  <br>
  <input id=“medication” name=“medication” type=“text” required>
  <br>
  <input type=“submit” value=“Submit”>
</form>

 

This renders a text box, and if we try to submit the <form> without filling it out we get this message:

The styling of the message is specified by the browse, the picture above depicts the message in a Chrome browser. Don’t be surprised if you see something different in other browsers, it works the same!

Set a Minimum and Maximum

Another built-in validation is assigning a minimum or maximum value for a numeric fields like <input type=”number”>and <input type=”range”>. There are min  and max attributes for these fields. Take a look at the example:

 

<form action=“/example.html” method=POST>
  <label for=“age”>Your age:</label>
  <input id=“age” name=“age” type=“number” min=“0”>
  <input type=“submit” value=“Submit”>
</form>

 

A person’s age can not be a negative number. We have assumed that babies under 1 are considered 0 years old 🙂

If a user tries to submit an input that is less than 1 a warning will appear:

The same happens when you specify a max attribute.

Checking Text Length

 

There are certainly cases where we wouldn’t want our users typing more than a certain number of characters (think about the message cap for Twitter). We might even want to set a minimum number of characters. Conveniently, there are built-in HTML5 validations for these situations.

To set a minimum number of characters for a text field, we add the minlength attribute and a value to set a minimum value. Similarly, to set the maximum number of characters for a text field, we use the maxlength attribute and set a maximum value. Let’s take a look at these attributes in code:

<form action=“/example.html” method=“POST”>
  <label for=“username”>Enter a valid username: (between 5 to 30 characters)</label>
  <input id=“username” name=“username” type=“text” minlength=“5” maxlength=“30” required>
  <input type=“submit” value=“Submit”>
</form>

 

If a user tries to submit the <form> with less than the set minimum, this message appears:

And if a user tries to type in more than the maximum allowed number of characters, they just simply can’t!

Matching a Pattern

In addition to checking the length of a text, we could also add a validation to check how the text was provided. Sometimes we want the text to match a particular pattern. A pattern attribute has been provided for that. We can assign a regular expressions or regex to the pattern attribute. Regular expressions are a sequence of characters that make up a search pattern. If the input matches the regex, the form can be submitted.

Let’s say we wanted to check for a valid credit card number (a 14 to 16 digit number). We could use the regex: [0-9]{14,16} which checks that the user provided only numbers and that they entered at least 14 digits and at most 16 digits. To add this to a form:

<form action=“/example.html” method=“POST”>
  <label for=“payment”>Credit Card Number (no spaces):</label>
  <br>
  <input id=“payment” name=“payment” type=“text” required pattern=“[0-9]{14,16}”>
  <input type=“submit” value=“Submit”>
</form>

 

With the pattern in place, users can’t submit the <form> with a number that doesn’t follow the regex. When they try, they’ll see a validation message like so:

If you want to find out more about Regex, read more at MDN’s regex article.

Review

You are now able to take advantage of <form> element and collect information from the user! What we learned in this lesson can be summarized as follows:

  • The purpose of a <form> is to allow users to input information and send it.
  • The <form>‘s action attribute determines where the form’s information goes.
  • The <form>‘s method attribute determines how the information is sent and processed.
  • To add fields for users to input information we use the <input> element and set the type attribute to a field of our choosing:
    • Setting type to “text” creates a single row field for text input.
    • Setting type to “password” creates a single row field that censors text input.
    • Setting type to “number” creates a single row field for number input.
    • Setting type to “range” creates a slider to select from a range of numbers.
    • Setting type to “checkbox” creates a single checkbox which can be paired with other checkboxes.
    • Setting type to “radio” creates a radio button that can be paired with other radio buttons.
    • Setting type to “list” will pair the <input> with a <datalist> element.
    • Setting type to “submit” creates a submit button.
  • A <select> element is populated with <option> elements and renders a dropdown list selection.
  • A <datalist> element is populated with <option> elements and works with an <input> to search through choices.
  • A <textarea> element is a text input field that has a customizable area.
  • When a <form> is submitted, the name of the fields that accept input and the value of those fields are sent as name=value pairs.
  • Client-side validations happen in the browser before information is sent to a server.
  • Adding the required attribute to an input related element will validate that the input field has information in it.
  • Assigning a value to the min attribute of a number input element will validate an acceptable minimum value.
  • Assigning a value to the max attribute of a number input element will validate an acceptable maximum value.
  • Assigning a value to the minlength attribute of a text input element will validate an acceptable minimum number of characters.
  • Assigning a value to the maxlength attribute of a text input element will validate an acceptable maximum number of characters.
  • Assigning a regex to pattern matches the input to the provided regex.
  • If validations on a <form> do not pass, the user gets a message explaining why and the <form> cannot be submitted.

 

Using the <form> element in conjunction with the other elements listed above allows us to create websites that interact with users.