HTML Forms

HTML forms are used to get user input data from a webpage.

Text Input Tags

Input tags allow a user to input data into a form. There are various means of getting an input. The type attribute is used to identify the type of input that a given input tag accepts. The text input type includes:

Input of type "text" presents the user with a textbox.

<input type = "text">
You can type inside the "text" input box here:

Each input tag should have a name associated with it. The name attribute is associated with the data that the user inputs into the input tag when the data is sent to another webpage. We shall see how this works further down in these notes. Within a given form, each input tag should have a unique name. For the moment, we just need to get into a habbit of attaching a name attribute to all input tags, as shown below.

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

Input of type "textarea" is used to create a text area. The attribute rows and cols are used to specify the text area's size.

Input of type "password" keeps the user's keystrokes hidden.

Example of the text input types (Run Example)

<form>
<p> This is a text field 
<input type = "text" name = "textField">
</p>

<p>This is a text area 

<textarea name = "textareaField" rows = "5"></textarea>
<br>   
It has been set to display five lines of text.
Note that textarea is declared differently to other input types</p>

<p> This is a password 
<input type = "password" name = "passwordField">
</p>
</form>
      

An image can be used as a background for any element. Write code to use an image as a form background, as shown here.

Labels

The <label> tag defines a label for an <input> element. A label can be tied to an input by using the "for" attribute. The "for" attribute of the <label> tag must be equal to the id attribute of the related element to bind them together. Normally, we can give the id attribute the same value as the name attribute (radio buttons are an exception to this rule). Clicking on a label that is tied to an input causes the input to be selected, as shown in the example below:

Example of a form label (Run Example)

<form>
<label for = "name1">Name 1: </label>
<input type = "text" id = "name1" name = "name1"><br>
<label for = "name2">Name 2: </label>
<input type = "text" id = "name2" name = "name2"><br>
<label for = "name3">Name 3: </label>
<input type = "text" id = "name3" name = "name3">
</form>
<p>Clicking on the "Name 1: ", 2 or 3 labels above will select the associated text input field.

Placeholder Text

Placeholder text is is used to provide an input hint to the user. It is displayed inside an input field as long as the field is empty. As soon as you start typing, the placeholder will disappear.

<input type = "text" name = "user_name" placeholder = "Enter your username">

Pre-Assigned Value

The value attribute is used to pre-assign values to text and textarea fields. The pre-assigned value is an actual value that will not automatically disappear when you start typing.

<input type = "text" name = "textField" value = "Some pre-assigned text">
      

Buttons

A button is a clickable button that can drive some JavaScript code.

A reset button clears all elements in a form.

A submit button causes a form to be processed.

 

Buttons, reset buttons and submit buttons do not need to have a name attribute associated with them, as they are not ways of inputting data in a form. Instead, they are actions for driving the form.

The value attribute is used to place text onto to a button, reset button or submit button.

 

Example of a form that uses a button, reset button and submit button, along with values for the various buttons (Run Example)

<form>
<p>Here is a button 
<input type = "button" value = "Example Button">
</p>
   
<p>Here is a reset button 
<input type = "reset" value = "Reset">
</p>
   
<p>Here is a submit button
<input type = "submit" value = "Submit">
</p>
</form>

Write code to create a form that allows a user to input a name and address. The user should be able to reset or submit the form, as shown here.

Select

The select tag is used to contain either a drop-down menu or a list. If the size attribute is not set or if it is set to size = "1" then a drop-down menu is displayed. Setting the size to any value greater than 1 displays a list. By default, the size is set to 1, so the default display is a drop-down menu.

Each item in the drop-down menu or list is contained within an option tag. The option tag contains a value attribute. This specifies the value that will be sent if that option is selected when the form is submitted.

Example of a select drop-down menu and a list (Run Example)

<form>
<h3>Below is a list.</h3>
<select name = "list" size = "5"> 
<option value = "10">item 1</option>
<option value = "20">item 2</option>
<option value = "30">item 3</option>
<option value = "40">item 4</option>
<option value = "50">item 5</option> 
<option value = "60">item 6</option>
<option value = "70">item 7</option>
<option value = "80">item 8</option>
<option value = "90">item 9</option>
<option value = "100">item 10</option> 
</select>
<p>
   It has been set to have a height of 5.<br>No item has been set to be initially selected.<br>
<br> 
<h3>Below is a drop down menu</h3>
<select name = "menu"> 
<option value = "one">menu item 1</option>
<option value = "two">menu item 2</option>
<option value = "three" selected>menuItem3</option>
</select>
<p>
   Item 3 has been set to be initially selected.
   </p>
</form>

 

Setting the attribute multiple will allow for multiple items in a list to be selected. Multiple selection is made using the mouse while holding down the control key or the shift key.

<select name = "menu" multiple> 

Write code to allow a user to select multiple fruit items from a list box, as shown here.

Checkbox

The checkbox input allows a user to check items from a list of items. By default, check boxes initially appear without a check mark. Use the checked attribute to display a check mark.

Example of a checkbox (Run Example)

<form>
<p>The last two checkboxes are pre-checked below.</p>
<input type = "checkbox" name = "checkbox1" value = "a">
<input type = "checkbox" name = "checkbox2" value = "b" checked>
<input type = "checkbox" name = "checkbox3" value = "c" checked> <br> <input value = "Submit" type = "submit" />
</form>

Write code to allow a user to check colour combinations and submit their selection, as shown here.

Radio Buttons

The radio button input type allows a user to select exactly one from a selection of items. Items that have the same name attribute are grouped together, as shown in the example below:

Example of a radio button (Run Example)

<form>
<p>Here is a group of radio buttons 
<input type = "radio" name = "radiobuttonGroup1" value = "1" checked> <!-- The checked attribute is used to set the default selected item -->
<input type = "radio" name = "radiobuttonGroup1" value = "2">
Item one has been set to be initially selected.</p>

<p>Here is a second group of radio buttons
<input type = "radio" name = "radiobuttonGroup2" value = "one">
<input type = "radio" name = "radiobuttonGroup2" value = "two">
<input type = "radio" name = "radiobuttonGroup2" value = "three">
No item has been set to be initially selected.</p>
<input value = "Submit" type = "submit" /></form>

 

 

Write code to allow a user to select a model and colour of a car and to submit this data, as shown here.

Fieldset

Fieldset tags are used to group related form data together. A fieldset will draw a box around the items that it contains.

Example of a fieldset tag (Run Example)

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

<label for = "address">Address:</label>
<input type = "text" id = "address" name = "address"  autocomplete = "off">
<br>

<label for = "phone">Phone:</label>
<input type = "tel" id = "phone" name = "phone">
</fieldset>
<br>

<input type = "submit" value = "Submit">
</form>

Write code to allow a user to enter their profile into a form, as shown here.

Extend the BMW car example, so that it uses fieldsets to seperate the model and car colour, as shown here.

Legend

A legend tag is used to place a heading on a fieldset, as shown in the example below.

Example of a legend (Run Example)

<form>
<fieldset>
<legend>Personal Details</legend>
<label for = "name">Name:</label>
<input type = "text" id = "name" name = "name">
<br>

<label for = "address">Address:</label>
<input type = "text" id = "address" name = "address" autocomplete = "off">
<br>

<label for = "phone">Phone:</label>
<input type = "tel" id = "phone" name = "phone">
</fieldset>
<br>

<input type = "submit" value = "Submit">
</form>

A fieldset can contain other fieldsets. Extend the personal profile code above so that is has a container fieldset, as shown here.

Extend the BMW example so that it uses legends instead of h2 tags, as shown here.

File

The file input type allows a user to select a filename.

Note that, although the filename is selected and can be submitted to another webpage, the actual file content is not uploaded. To do this requires server-side code, such as php.

Example of a File selection input (Run Example)

<form>
<input type = "file" name = "file">
</form>

 

Using the accept attribute restricts the files that can be selected for uploading. In the example below, only image files will be displayed for selection.

Example using a file accept attribute (Run Example)

<form>
<p>Select an image file:
<input type = "file" name = "imageFile" accept = ".jpg, .gif, .png">
</p>
</form>

Hidden Fields

The input type hidden is used to hold data that is not displayed on the screen. Hidden input is used to hold data when programming in JavaScript. The data that is contained in a hidden input is sent to a new webpage along with the other input data when a form is submitted.

When you submit the form below you will see that the hidden value has been sent as part of the url.

Example of a hidden input (Run Example)

<form>
<input type = "hidden" name = "hiddenName" value = "123">
<input type  = "submit" value = "Submit">
</form>

Form Actions

The action attribute identifies the action that is to happen to a form when it is submitted by a user. When a form is submitted, it will either be sent to another webpage to be processed or it will be emailed to some address.

To send the form data to another webpage, use the action below:

<form action = "http://www.somewebpage.com">

To email a form, use the action below. Note that email addresses need to have the suffix mailto:

<form action = "mailto:admin@mycompany.com">

Method

The method atrribute defines how a form's data should be sent when a user submits the form to another webpage. Data can be sent using either a "get" or a "post" method.

Data sent using the "get" method is appended to the webpage url that appears in the browser window.

Using the get method a user can see a form's values in a url. This:

However:

The "post" method hides the form data when it is being sent to another webpage. Therefore, we can use post to send password details to another webpage. As post data is hidden, post cannot be used for either book-marking or as a debugging aid.

There is no limit to the size of a post, so post should be used to send large amounts of data to another webpage.

 

The filename assigned to the "action" attribute must exist. For the example below to work, the file "form_demo.html" must exist.

Example form using a "get" method (Run Example)

<form action = "form_demo.html" method = "get" target = "_blank">

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

<label for = "password">Password: </label>
<input type = "password" id = "user_password" name = "user_password">
<br>

<input type = "submit" value = "Submit">
</form>

Change the method in the code above to "post" and see that the submitted url does not contain any form data, as shown here.

Write code to produce a form that asks a user to enter their name, address and phone number and lets the user submit this data, as shown here.

Write JavaScript code to extract and display the name, address and phone number from the submitted form in the question above, as shown here.

Autofocus

The Autofocus attribute forces the input to focus on the element that has autofocus set.

Example of a form with autofocus set (Run Example)

<form>
<label for = "user_name">name:</label>
<input id = "user_name" name = "user_name" autofocus>
<br>

<label for = "address">address:</label>
<input id = "address" name = "address">
<br>

<label for = "age">age:</label>
<input id = "age" name = "age">
<br>    

<input type = "submit" value = "Submit">
</form>

Write code to place the autofocus on the age field instead of the name field.

Write code to see what happens when you place an autofocus on more than one field?

Email Addresses

Setting the input type to be "email" will only allow valid email addresses to be submitted.

On the virtual keypad of a mobile device, the keyboard will change to be appropriate for inputting emails. For example, the "@" key will be made available.

<input type = "email">

Write code to see what happens if you try to submit a form that contains a non-valid email field, as shown here.

Form Validation

The "email" type performs automatic form validation. It will not allow a form to be submitted if the email is not valid.

The types listed below also support automatic form validation:

Novalidate

Setting the form attribute "novalidate" will turn automatic validation off.

Example of a form that has the "novalidate" attribute set (Run Example).

<form novalidate>    
<input type = "email">
<br>    

<input type = "submit" value = "Submit"> 
</form>

 

Url Addresses

Setting the input type to be "url" does not have any affect on users who are using a full size, laptop or PC, keyboard. However, virtual keypads on mobile devices will change the keyboard to be appropriate for inputting emails. For example, a ".com" key will be made available.

<input type = "url">

Search Boxes

Setting the input type to be "search" will provide a cancel icon within the input field. This allows users to easily change their search input.

<input type = "search">

Write code to make a search form. A user should be able to enter a search term and submit it to google, as shown here.

Number Spinbox

Setting the type to be "number" ensures that only a number can be entered into the field. The field will show spinbox icons so that the user can iterate up and down through the number range.

<input type = "number">

 

The minimun and maximum range can also be set

<input type = "number" min = "20" max = "100">

 

The minimun and maximum range can also be set, as can a step size and a default start value, as shown in the example below.

<input type = "number" min = "20" max = "100" step = "10" value = "40">

Number Slider

Setting the type to be "range" will set a number range to appear as a slider.

<input type = "range" min = "20" max = "100" step = "10" value = "40">

Write javascript code to display the current value of the slider, as shown here.

Date Picker

Setting the type to be "date" will let the user select from a calander.

<input type = "date">

Click on the field below to see the "date" type working.

 

The type can also be set to "time", "month" or "week".

<input type = "time">
<input type = "month">
<input type = "week">

Click on the field below to see the "time" type working.

Click on the field below to see the "month" type working.

Click on the field below to see the "week" type working.

Telephone Number

Setting the type to be "tel" informs the browser that the user should be inputting a telephone number.

NOTE: tel is currently not validated by any broswer

<input type = "tel">

Write code to allow a user to submit a telephone number, as shown here.

Pattern

Regular expressions allow us to validate HTML input, so that only certain patterns of characters are accepted. The "pattern" attribute specifies a regular expression that an element's value is checked against when a form is submitted. It uses the exact same syntax as JavaScript regular expression do. The "pattern" attribute can be used on the elements listed below:

In HTML, regular expressions take the form below

pattern="patternString"

A pattern is made up of one or more sub-patterns.
Each sub-pattern is of the form
([]{})
Where:

() is used to contain each pattern
If there is only one pattern, then these brackets are not needed.
[] contains the valid characters within a pattern
If there is only one character, then this is not needed. The [] can contain ranges of characters. For example:
[a-zA-Z0-9] will allow for the letters a-z and the digits 0-9.

The ^ symbol can be used in conjunction with the [] to allow for any characters that are not inside the []. For example:
[^a-zA-Z] will match everything except letters.
{} states how many times the characters must appear in a pattern
The {} can contain ranges. For example:
{4-9} means at least four characters and at most nine characters.
{4,} means at least four characters
{,9} means at most nine characters.
Use the '*' character to require 0 or more characters and use the '+' character to require 1 or more characters.

 

Various patterns of characters can be matched within a pattern:

.
any character including spaces and tabs.
?
characters MIGHT be there, but do not have to be in the pattern
?=.*
characters MUST occur at some point in the pattern
\d
a digit
\s
whitespace
\S
non-whitespace
\W
any letter, number or the underscore character
^
start of a pattern. For example: ^DkIT will match "DkIT is in County Louth", but not "Welcome to DkIT"
$
end of a pattern. For example: DkIT$ will match "Welcome to DkIT", but not "DkIT is in County Louth"
^ $
combining ^ and $ around a string will look for an exact match. For example ^DkIT$ will only match "DkIT". It will not match "DkIT is in County Louth" or "Welcome to DkIT"
|
used to match one OR another pattern. For example (a-z) | (A-Z){3}
\
Escape character that is used to select any of the above special characters that are used in patterns. For example: \| means the '|' character and not the OR operation.
 

Click here to see the full set of regular expressions.

Click here for a detailed lesson on regular expressions.

 

In the pattern below, the user must input a seven digit number (Run Example).

<input type="text" pattern="[0-9]{7}">

 

In the pattern below, the user must input a decimal number (Run Example).

<input type = "text" pattern = "[0-9]+\.[0-9]+">

 

In the pattern below, the user must input a ten-digit mobile telephone number that begins with 083, 085, 086 or 087 (Run Example).

<input type="tel" pattern="08[3567]{1}[0-9]{7}">

 

When using regular expressions, it is important to inform the user of the expected format. The default error message that is given for an incorrect regular expression is the generic string “Please match the requested format.”. If it exists, then the value in the “title” attribute of an input element will appear after the generic message.

In the example below, the user is informed that a valid mobile telephone number is required (Run Example).

<input type="tel" pattern="(08)([3567]{1})([0-9]{7})" title="Enter a ten-digit number that begins with 083, 085, 086 or 087">

 

In the pattern below, the user must input a valid date (dd-mm-yyyy) (Run Example)

<input type="text" pattern="(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d">

Write code to accept a date in the American format mm-dd-yyyy, as shown here.

Write code to accept a date in the format dd-mmm-yyyy, using lowercase jan, feb, mar... as the month, as shown here.

Adjust the example above, so that the months can be any combination of lowercase and uppercase letters, such as JAN, Feb, mar, ApR, as shown here.

In the pattern below, the user must input at least one one digit and one lowercase letter (Run Example)

<input type="text" pattern="(?=.*[0-9])(?=.*[a-z]).+">

Adjust the code above, so that the user has enter at least one digit and one letter (either uppercase or lowercase), as shown here.

Write code to force the user to input a password that must contain an uppercase letter, a lowercase letter, a digit and one of these characters (£!#€$%^&*). In addition, the password should be at least ten digits long, as shown here.

In the pattern below, the user must input a valid email (Run Example)

<input type="text" pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}">

Write code to only allow valid lowercase DkIT emails (i.e. end with "@dkit.ie" or "@student.dkit.ie") to be submitted, as shown here.

Adjust the code above, so that the user can enter their DkIT email in upper and lower case letters, as shown here.

Go online and find a regular expression to validate international telephone numbers using the EPP format, as shown here.

Go online and find a regular expression to validate credit card numbers, as shown here.

Colour Picker

Setting the type to be "color" will let the user select a colour from a colour picker.

<input type = "color">

Click on the colour selector below to see it working.

Write javascript code to allow the user to change the background colour of a webpage, as shown here.

Required Fields

Setting the "required" attribute for a field will force the user to enter a value for the field before they can submit a form.

<input type = "email" required>

Write code that forces a user to enter a name and an email before the allowing the user to submit a form, as shown here.

Autocomplete Attribute

The autocomplete attribute specifies whether a form or input field should have autocomplete on or off. When autocomplete is turned on, the browser automatically completes values, based on values that the user has entered before. It is possible to have autocomplete 'on' for the form, and 'off' for specific input fields, or vice versa.

The autocomplete attribute works with <form> and the following <input> types: text, search, url, tel, email, password, datepickers, range, and color.

In the code below, autocomplete has been enable for all fields in the form, except the address field.

Example using autocomplete (Run example)

<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search example</title>
</head>

<body>

<form autocomplete = "on">
<label>Name:</label>
<input type = "text" id = "name">
<br>

<label>Address:</label>
<input type = "text" id = "address"autocomplete = "off">
<br>

<label>Phone:</label>
<input type = "tel" id = "phone">
<br>

<input type = "submit" value = "Submit">
</form>

<p>Input a name, address and phone number.<br>
Refresh the page<br>
Begin to input the same values again. Autocomplete will work on the name and telephone. It has been turned off for the address.</p>
</body>
</html>

Disabling Enter Key Submission Event

By default, forms are submitted when the Enter key is pressed. Unless the form is being fully validated on the client-side, it is usually desirable to disable the Enter key.

Write code to disable the Enter key in a form that has a name, address and gender, as shown here. Note that the textarea needs to have the Enter key enabled, as it is used to place a linebreak in the textarea.

Client Side Form Validation

A JavaScript function can be called when a form is submitted. This function can be used to perform validation on the form data.

 

<script>
<script>
function myFormValidationFunction()
{ // validate the form // return true if the form data is valid and false if the form data is not valid // If you return false, then the form will not be submitted ...
}
</script> <form action = "form_demo.html" onsubmit = "return myFormValidationFunction()"> ... </form>

The example below marks all of the fields that a user leaves blank.

Example of a Custom Submit Function (Run Example)

<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form function Example</title>
<script>
let formHasNoErrors = true;

/* Each input element that needs to be validated needs its own validation function */
function isNameValid()
{
    // test to see if the name is not empty

    if (document.getElementById("name").value.length === 0)
    {
        document.getElementById("nameErrorMessage").innerHTML = "Please enter a name";
        return false;
    }
    else
    {
        document.getElementById("nameErrorMessage").innerHTML = "";
        return true;
    }
}

function isAddressValid()
{
    // test to see if the address is not empty
    if (document.getElementById("address").value.length === 0)
    {
        document.getElementById("addressErrorMessage").innerHTML = "Please enter an address";
        return false;
    }
    else
    {
        document.getElementById("addressErrorMessage").innerHTML = "";
        return true;
    }
}
/************************************************************************************/


/* The form needs one main wrapper function that will call each of the input element validation functions above */
function isFormValid()
{
    /* Validate all of the input elements */
    let nameIsValid = isNameValid();
    let addressIsValid = isAddressValid();

    /* If ALL of the element validation functions pass, then the form is valid */
    if (nameIsValid && addressIsValid)
    {
        return true;
    }
    else /* If ANY of the element validation functions fail, then the form fails */
    {
        return false;
    }
}
</script>
</head>

<body>
<form action = "form_demo.html" onsubmit = "return isFormValid()">

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

<label for = "address">Address:</label>
<textarea rows = "5" id = "address" name = "address"></textarea><label id ="addressErrorMessage"></label>
<br>

<input type="submit">
</form>
</body>
</html>

Write code to validate a form that contains a name, address and phone number prior to submitting the form. All three fields must contain a value, the address must include at least two lines and the phone number must contain only digits and be seven digits long, as shown here.

 
<div align="center"><a href="../../versionC/index.html" title="DKIT Lecture notes homepage for Derek O&#39; Reilly, Dundalk Institute of Technology (DKIT), Dundalk, County Louth, Ireland. Copyright Derek O&#39; Reilly, DKIT." target="_parent" style='font-size:0;color:white;background-color:white'>&nbsp;</a></div>