HTML Forms
Form structure
In HTML, form elements such as text fields, buttons, and checkboxes are usually placed inside a <form> element. This allows the browser to properly group them together and submit their values when the form is submitted.
Typically, a form is structured like this:
<form action="submit.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<input type="submit" value="Submit">
</form>
- The
<form></form>element acts as a container for all the input fields. - When the Submit button is pressed, the data from all input fields within the form is sent to the server (specified in the action attribute).
However, HTML5 introduces a new way to associate form elements with a form even if they are placed outside the <form> element. This is done using the form attribute.
In teh example below,the input field and a submit button are linked to a form, even though the button is placed outside the form.
Example: Input Outside the Form
<form id="myForm">
<input type="text" name="username" placeholder="Enter your username">
</form>
<input type="submit" form="myForm" value="Submit">
Why Use the form Attribute?
- Flexibility in Page Layout: Allows form elements to be positioned anywhere in the HTML structure.
- Reusability: Multiple elements can be linked to the same form, even if they are in different sections.
- Better UX Design: Useful for multi-step forms where fields appear in different locations.
- Accessibility: Enables dynamic form handling without breaking form submission.
More Examples
Example 1: Two Submit Buttons Controlling the Same Form
<form id="registerForm">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
</form>
<input type="submit" form="registerForm" value="Register">
<input type="submit" form="registerForm" value="Sign Up">
Example 2: Reset Button Outside the Form
<form id="userForm">
<label for="age">Age:</label>
<input type="number" id="age" name="age">
</form>
<input type="reset" form="userForm" value="Reset Form">
- The
formattribute must match theidof the target form. - Elements linked with
formmust still have anameattribute for submission. - Avoid overusing external form elements, as it can make the layout confusing.
Please Note: Using the
form attribute in HTML5 allows developers to position form inputs anywhere on a webpage while still linking them to a form. This feature enhances layout flexibility, enables better user experiences, and supports complex form designs. However, use it carefully to maintain clarity in form submission behavior. Form Filling
Forms are typically used to request a user to enter some information. When he/she has finished filling in the form, the entered data can be sent to a server-side script or to someone by email for processing. The scripts resides and runs on the machine running the web server from which web pages are delivered. The attributes of the <form> tag, apart from the form attribute we discussed above, include:
| form attribute | Description |
|---|---|
action="http://host/cgi-bin/script_name" | After the form has been filled in, the entered data is sent to the named (by the action attribute) server-side script for processing. |
action="mailto:name@site" | After the form has been filled in, the entered data is sent to the named (by the ACTION attribute) person by email. |
method="get" | The browser tacks the query string onto the end of the script's URL, and fetches it from the HTTP server using the usual get request. Fill in the box below, hit return and check out our browser location window: |
method="post" | The browser uses the post method to submit the content of the form to the server. In this mode, the HTTP server opens up a communication channel between the browser and the executable script, and the browser sends the query string directly. |
Text input
A form to request the user to enter some text is shown below. A simple text window which consists of a single line of 20 characters is introduced by the <input> tag as illustrated below:
| Displayed by browser | HTML markup required |
|---|---|
|
The data in the input field can be initialized to a particular value using the value attribute:
| Displayed by browser | HTML markup required |
|---|---|
|
The input data is sent in the form: name=Your+name
It is also possible to specify the maximum length for a text to be entered:
| Displayed by browser | HTML markup required |
|---|---|
|
You can use the pattern attribute for custom input validation (e.g., a phone number format).
| Displayed by browser | HTML markup required |
|---|---|
|
To allow users enter a postcode that follows the UK postcode system (like NW1 5LS), you should create a patters that allows variations such as:
- "NW1 5LS" (Letter-Letter-Digit Space Digit-Letter-Letter)
- "E1 6AN" (Letter-Digit Space Digit-Letter-Letter)
- "WC2H 7LT" (Letter-Letter-Digit-Letter Space Digit-Letter-Letter)
<input type="text" name="postcode" id="postcode"
pattern="^[A-Z]{1,2}[0-9][0-9A-Z]? [0-9][A-Z]{2}$"
title="Enter a UK postcode in the format NW1 5LS" required>
| Explanation of the Pattern | |
|---|---|
| Pattern | Meaning |
^ |
Start of input |
[A-Z]{1,2} |
1 or 2 uppercase letters (e.g., NW, E, WC) |
[0-9] |
A single digit (e.g., 1) |
[0-9A-Z]? |
Optional digit or letter for extended postcodes (e.g., "WC2H") |
|
A space (mandatory) |
[0-9] |
A single digit (e.g., 1) |
[A-Z]{2} |
Two uppercase letters (e.g., LS) |
$ |
End of input |
HTML5 allows autocomplete="on" or off to help browsers autofill forms.
| Displayed by browser | HTML markup required |
|---|---|
|
<input> tag include:
| input attribute | Description |
|---|---|
type="text" | Defines a one line text input field |
name="registration" | Names the argument which is sent |
value="w1234567" | The value of the argument |
size="8" | The width of the input area |
maxlength="8" | The maximum number of characters which can be entered in the field |
pattern="[0-9]{5}" | For custom input validation (e.g., a phone number format) |
In sending the data there are various character mappings of the input data to ease later processing. For example:
| Input Character | Sent |
|---|---|
| space | + |
| = | %3D |
| Line Feed | %0A |
| % | %25 |
| & | %38 |
| Carriage Return | %0D |
Labels
The <label> element represents a caption for the form element it is associated with. The <label> can also add as an accessibility aid to forms:
- they can widen the element clickable area
- they help screen readers identify fields on a web page
Implicit Labels
Implicit labels are wrapped around a form control. Implicit labels are not well suported in older screen readers, and are harder to style with CSS
| Displayed by browser | HTML markup required |
|---|---|
|
Explicit Labels
Explicit labels are separate from the form control, and linked to their form control via the for attribute. The for attribute of the label has to match the id attribute of the form control it is linked to. Explicit labels are well supported by screen readers and are easy to style using CSS. We will be using explicit labels in the notes.
| Displayed by browser | HTML markup required |
|---|---|
|
Multiple lines of text input - Textarea
A form to request the user to input multiple lines of input uses the <textarea> and its corresponding </textarea> tag. So that the user can enter multiple lines the <input type="submit"> tag is used to signal when the form has been completed. For example:
| Displayed by browser | HTML markup required |
|---|---|
|
Please note: If no
rows or cols attribute values are specified, the default values of 2 and 20 will be used for rows and cols respectively. The size of the textarea can also be defined in CSS using height and width. | |
<textarea> tag include:
| input attribute | Description |
|---|---|
name="feedback" | Specifies a name for the parameter to be passed to the form-processing application. |
rows="5" | Defines the number of rows visible (by defult 2). |
cols="30" | Defines the number of columns visible (by defult 20). |
Password
A form to request a password or any secret text to be entered is:
| Displayed by browser | HTML markup required |
|---|---|
|
Radio buttons
A form to request the user to select from one of a series of radio buttons uses the <input> tag with an attribute of type="radio". Only one radio button per group of radio buttons with the same name can be checked. An example of a radio button input form to select the delivery time is shown below:
| Displayed by browser | HTML markup required |
|---|---|
|
The optional attribute checked can be added to one of the input type="radio" tags to set a default selection. For example:
| Displayed by browser | HTML markup required |
|---|---|
|
Checkboxes
A form to request the user to select from one one or more check boxes uses the <input> tag with an attribute of type="checkbox". An example of a checkbox form is shown below:
| Displayed by browser | HTML markup required |
|---|---|
|
| |
Pop up List
A form to allow the user to select an item from a pop-up list uses the <select> tag. An example of a pop-up list is shown below:
| Displayed by browser | HTML markup required |
|---|---|
|
| |
The <select> tag encloses the tag:
<option></option>- Which names a value in the pop-up list. The
<option> tag may have an attribute of selected to define the initial value of the pop-up list.Scrolling List
A form to allow the user to select one or more item from a list uses the <select> tag with the multiple attribute. An example of a scrolling list is shown below:
| Displayed by browser | HTML markup required |
|---|---|
|
| |
The optional size attribute defines the size of the displayed list. If the specified size is smaller than the number of option items, a vertical scroll bar will automatically be displayed, to allow the user to view all the different items. If multiple is used and no size is specified, the default size is usually 4 (or will automatically fit the number of items in the option list).
Datalist
datalist is an HTML5 element. The datalist represents a list of options available for its parent element. The datalist can be paired up with an <input type="text" list="idOfList"> for example, and the datalist may be displayed by the browser and/or be used for autocompletion as the user types into the input field.
Current Browser Support for datalist
| Displayed by browser | HTML markup required |
|---|---|
|
| |
input is linked to the datalist via the list attribute which matches the id of the datalist.option elements in the datalist do not require a closing tag.Email input field
email is an HTML5 input type. This input type is designed to let the user enter an email address. Browsers that support this input type will automatically check the validity of the format of the data entered and alert the user if the format is invalid. If the browser doesn't support this input type, it will automatically fall back to the type="text"
| Displayed by browser | HTML markup required |
|---|---|
|
email soft keyboard will be launched when filling in this input field rather than the default text keyboard, which will enhance the user experience and speed of data entry.URL input field
url is an HTML5 input type. This input type is designed to let the user enter a URL. Browsers that support this input type will automatically check the validity of the format of the data entered and alert the user if the format is invalid. If the browser doesn't support this input type, it will automatically fall back to the type="text"
| Displayed by browser | HTML markup required |
|---|---|
|
url soft keyboard will be launched when filling in this input field rather than the default text keyboard, which will enhance the user experience and speed of data entry.Tel input field
tel is an HTML5 input type. This input type is designed to let the user enter a telephone number. Browsers will not automatically check the validity of the format of the data entered as the format of telephone numbers varies so much around the world. If the browser doesn't support this input type, it will automatically fall back to the type="text"
| Displayed by browser | HTML markup required |
|---|---|
|
tel soft keyboard will be launched when filling in this input field rather than the default text keyboard, which will enhance the user experience and speed of data entry.Number input field
number is an HTML5 input type. This input type is designed to let the user enter a number. Browsers that support this input type will automatically check the validity of the format of the data entered and alert the user if the format is invalid. The browser may also display up and down arrows for the user to click on to increase and decrease the value entered. If the browser doesn't support this input type, it will automatically fall back to the type="text"
| Displayed by browser | HTML markup required |
|---|---|
|
You can also allow decimal values by adding a value with a decimal point or a step with decimal point.
The attributes of the<input type="number"> element include:
| input attribute | Description |
|---|---|
value="10" | Defines the default value |
step=".1" | Defines the step between values and as a result defines valid values |
min="0" | Defines the minimum value allowed |
max="100" | Defines the maximum value allowed |
| Displayed by browser | HTML markup required |
|---|---|
|
number soft keyboard will be launched when filling in this input field rather than the default text keyboard, which will enhance the user experience and speed of data entry.Search input field
search is an HTML5 input type. This input type is designed to let the user enter a search query. Browsers that support this input type may style it differently from the text input and may automatically offer the possibility to clear the input field. If the browser doesn't support this input type, it will automatically fall back to the type="text"
| Displayed by browser | HTML markup required |
|---|---|
|
Here's a version with no CSS as the Bootstrap Library removes the delete icon from the search field: JS Bin on jsbin.com
Date & Time picker
There are a number of attributes that will create a date picker using the input element:
Date
date is an HTML5 input type. This input type is designed to let the user enter a date. Browsers that support this input type will automatically check the validity of the format of the data entered and alert the user if the format is invalid. The browser may also display a date picker. If the browser doesn't support this input type, it will automatically fall back to the type="text". You can provide a default value in the format yyyy-mm-dd, and you may use min and max date values if you want to retrict the valid date.
Current Browser Support for date and time input
| Displayed by browser | HTML markup required |
|---|---|
|
Time
time is an HTML5 input type that allows users to enter a time value (hours and minutes).
| Displayed by browser | HTML markup required |
|---|---|
|
Datetime-local
datetime-local is an HTML5 input type. This input type is designed to let the user enter a date and time in the user's local time zone. Browsers that support this input type will automatically check the validity of the format of the data entered and alert the user if the format is invalid. The browser may also display a date and time picker. If the browser doesn't support this input type, it will automatically fall back to the type="text". You can provide a default value in the format yyyy-mm-ddThh:mm, and you may use min and max date and time values if you want to retrict the valid date/time.
Current Browser Support for date and time input
| Displayed by browser | HTML markup required |
|---|---|
|
Week
week is an HTML5 input type. This input type is designed to let the user enter the week in a particular year. Browsers that support this input type will automatically check the validity of the format of the data entered and alert the user if the format is invalid. The browser may also display a date picker. If the browser doesn't support this input type, it will automatically fall back to the type="text". You can provide a default value in the format yyyy-Www, and you may use min and max date and time values if you want to retrict the valid week.
| Displayed by browser | HTML markup required |
|---|---|
|
Month
month is an HTML5 input type. Allows users to select a month and year without specifying a day.
| Displayed by browser | HTML markup required |
|---|---|
|
In both week and month you can always use the min and max attributes:
<input type="month" id="month" name="month" min="2020-01" max="2030-12">
Range input field
range is an HTML5 input type. This input type is designed to let the user enter a numerical value. Browsers that support this input type may style it differently from the text input and offer a slider. If the browser doesn't support this input type, it will automatically fall back to the type="text"
| Displayed by browser | HTML markup required |
|---|---|
|
You can use the min, max and step attributes to specify authorised values and define the granularity of the slider:
| input attribute | Description |
|---|---|
value="60" | Defines the default value |
step="10" | Defines the step between values and as a result defines valid values. The default step value is 1 |
min="0" | Defines the minimum value allowed. The default min value is 0 |
max="100" | Defines the maximum value allowed. The default max value is 100 |
| Displayed by browser | HTML markup required |
|---|---|
|
Color input field
color is an HTML5 input type. This input type is designed to let the user enter a color in hexadecimal format. Browsers that support this input type may style it differently from the text input and may automatically present a colour picker. If no default value is specified, the default #000000 is used.
Current Browser Support for input type="color"
| Displayed by browser | HTML markup required |
|---|---|
|
Hidden field in a form
Hidden fields are used to send parameters you don't want to appear in the displayed form. The name and value of the hidden field are incorporated into the parameter list sent, but do not have any visible counterpart on the form.
| Displayed by browser | HTML markup required |
|---|---|
|
Buttons
There are several ways to create a button on a form, and there are several types of buttons available. You can create a button by adding the type="button" attribute to the input element, or by using the button element. These two types of button will have no default behaviour, other than being a clickable button, and you will need to add some JavaScript to add event listeners to these buttons and add behaviour (for example calculating the total price of an order). Please see in the last section of this document for details on Submit buttons and Reset buttons.
| Displayed by browser | HTML markup required |
|---|---|
|
<input> vs. <button>
<button> is preferred to <input type="button">, this is because:
<button>allows richer content inside (e.g.,<i>,<span>).<button>can have CSS icons and images, while<input>only supports thevalueattribute.<button>is more readable and maintainable in modern HTML.
Useful Attributes
Readonly
It is possible to make fields read only by adding the readonly attribute in the form element's tag.
| Displayed by browser | HTML markup required |
|---|---|
|
Required
It is possible to make fields mandatory by adding the required attribute in the form element's tag. The browser may style the element differently to indicate that the field is mandatory.
| Displayed by browser | HTML markup required |
|---|---|
|
aria-required="true" - Specifies that a field is required for accessibility:
Autofocus
It is possible to make fields be selected by default by adding the autofocus attribute in the form element's tag.
| Displayed by browser | HTML markup required |
|---|---|
|
Placeholder
It is possible to add a placeholder in the input field by adding the placeholder attribute and spacifying a value in the form element's tag. The advantage of the placeholder over a default value, is that the placeholder automatically disappears when the user starts entering text, and will be displayed again if the user deletes what they entered, hence the information is never lost, and never needs additional user interaction to be removed.
| Displayed by browser | HTML markup required |
|---|---|
|
ARIA
The Accessible Rich Internet Applications (ARIA) attributes improve the usability of forms for users with disabilities, particularly those who use screen readers or other assistive technologies. ARIA attributes do not change the behavior of forms but provide additional information to assistive technologies.
| ARIA Description | Displayed by Browser | HTML Code Example |
|---|---|---|
| aria-required="true" - Specifies that a field is required for accessibility |
|
|
| aria-describedby - Links an input field to a description (e.g., error message) |
Invalid email address |
|
| role="group" aria-labelledby - Groups related fields for better screen reader support |
|
|
| aria-live="polite" - Announces validation messages to assistive technologies |
Must be at least 8 characters |
|
| role="button" tabindex="0" - Makes a div act like a button |
Submit Form
|
<div role="button" tabindex="0" onclick="alert('Submitted!')">
Submit Form
</div>
|
Putting it altogether
Fieldset and Legend
The fieldset element together with its corresponding legend are used to group several form controls and labels together.
| Displayed by browser | HTML markup required |
|---|---|
|
| |
Here's a version with no CSS as the Bootstrap Library changes the styling of the fieldset:
JS Bin on jsbin.com
Reset
The <input> tag with an attribute of type="reset" is used to reset the values in a form back to their default value. For example, the following form may be reset to its initial values by pressing the "reset" button.
| Displayed by browser | HTML markup required |
|---|---|
|
| |
Submit button
When a form contains a single entry field, the information is sent as soon as the user presses the "return" key. However, most forms will contain multiple form elements and therefore require a "submit button", generated by an additional tag <input type="submit"> to cause the submission of the input data:
| Displayed by browser | HTML markup required |
|---|---|
|
Which when pressed will send in addition to any information entered in the form the additional message button=Send.
When there are several elements in a form the data sent to the server-side script is composed of the individual elements concatenated together with an &. For example, when the Send button is pressed and the name Jane Smith is entered, then the following information will be sent: firstName=Jane&lastName=Smith&button=Send
<form> and </form> tags. If your submit button is not within those tags, the filled in elements will not be sent and any element outside those tags will not be submitted either. Make sure that if all your elements are to be dealt with as a single form, you should only have one <form> tag to start the form and one </form> tag to end the form.Styling the content of a form
You can add some styling to thefieldset and labels to ensure that the labels are well aligned to ensure readability of the form, see below:
JS Bin on jsbin.com
Emailing the content of a form
By adding the following attributes: method="post" action="mailto:Your e-mail address" enctype="text/plain" to your form element, when a user fills in and submits the form, the content of the form is posted to your e-mail address. Of course for this to work, the mail preferences must be set up in the users browser.
| Displayed by browser | HTML markup required |
|---|---|
|
Review Questions
- Question 1 - How to create a checkbox in HTML?
- <input type="checkbox">
- <input type="button">
- <checkbox></checkbox>
- <input type="check">
- Question 2 - How to create a radio button in HTML?
- <input type="radiobutton">
- <input type="button">
- <radio></radio>
- <input type="radio">
- Question 3 - How to create a textarea for multiple lines of comments in HTML?
- <input type="textarea">
- <input type="text" multiple>
- <textarea></textarea>
- <input type="text">