Web forms are used by virtually all websites for a wide range of purposes. Users of forums and social networks use forms to add content and interact with other users. Websites that can be customized to create a personalized experience, such as customizable newsfeeds, use forms to allow users to control the content that appears on the page. And nearly every website uses forms to allow website visitors to contact the organization or person administering the website. Web forms are made possible by the integration of multiple technologies:

  • HTML to create the form fields and labels and accept user input.
  • CSS to style the presentation of the form.
  • JavaScript to validate form input and provide Ajax-enabled interactions.
  • Server-side languages such as PHP to process form data.

In this guide, we're going to cover all of the HTML elements used to create web forms. We also have other tutorials that cover topics such as building a form, styling and designing forms, and ensuring form usability and accessibility.

Defining the Structure of a Form

Every web form must be wrapped in <form> tags. In most cases, all of the form fields will be nested between these tags. There are several attributes that may optional be used with the form element, including: accept-charset: This optional attribute is used to identify the character encodings acceptable to the server and code processing form input. If more than one encoding is specified, one space should be placed between each encoding. If left blank or not provided, the encoding will default to the same encoding as the document containing the form. action: This attribute is used to specify a URL where form data should be sent (for instance: http://example.com/form_file.php). This field was required prior to HTML5 but is now optional. autocomplete: Use this attribute if you want the visitors browser to suggest form responses based on saved entries. The default value is autocomplete="on". If you turn autocomplete off you must also turn it off on every field that may allow autocompletion. enctype: Used to specify how form data should be encoded. Only used if the method attribute mentioned below is set to post. There are three possible values:

  • application/x-www-form-urlencoded: The default value which replaces all spaces with "+" and converts all special characters to ASCII HEX values.
  • multipart/form-data: Nothing is encoded. Input is uploaded to the server exactly as it is entered into the form.
  • text/plain: Spaces are converted into "+" symbols, but not other characters are encoded.

method: Dictates the HTTP method a website visitors browser should use to submit form data. If post is specified, form data is enclosed in the body of the HTTP request. If get is specified, form data is appended to the end of the URL specified in the action attribute with a "?" symbol, data length is limited to 300 characters, and form input is visible and can be bookmarked. name: Similar to an id attribute, a name is a unique identifier that may only be used once within an HTML document and may be used to select the form with JavaScript or another scripting language. novalidate: Used to override the default validation of form data. target: Specifies where to display the response received after submitting the form.

  • _self loads the response in the same frame.
  • _blank opens a new window or tab.
  • _parent is used when a form is nested in a descendant browsing context to load the response in the parent context and behaves the same as _self is there is no parent context.
  • _top is similar to _parent but select the top level browsing context rather than the immediate parent context.

Grouping Form Fields

The <fieldset> element is used to group together related form fields. It may also be used to contain an entire form to provide a visual cue that distinguishes the form from surrounding content. The first element within a fieldset is usually a <legend>. The legend will be displayed a part of the fieldset border giving website visitors a clue about the purpose of a form. For example, if a contact form were nested within a web page full of otherwise unrelated content, the fieldset element could be used in combination with the legend element to isolate the contact form from the rest of the content both semantically and visually.

<p>Paragraph content.</p> <form>   <fieldset disabled>     <legend>Contact Form</legend>     <!--These elements are discussed later in this tutorial-->     <p>Name: <input type="text" size="30"></p>     <p>Email: <input type="text" size="30"></p>     <p>Subject: <input type="text" size="30"></p>     <p>Message: <textarea>Type your message here</textarea></p>     <p><input type="submit"></p>   </fieldset> </form>  <p>Additional paragraph content</p> 

When rendered in the browser, the contact form would be clearly separated from surrounding content.

Paragraph content.
Contact Form


Additional paragraph content

The fieldset element is optional but is commonly used to group related elements on long and complex forms, or to isolate form fields from nearby elements when a form is presented along with non-form content. HTML5 added three attributes which can be applied to fieldset elements:

  • disabled: Used to disable all of the forms in a fieldset. Note that we used this attribute in the example form above.
  • form: Used to associate a fieldset with the id of one or more form elements. Note that browser support for this attribute is very limited.
  • name: Associates a name with the fieldset.

The Input Element

Depending on the type of form you are creating, it's entirely possible to have a form that only includes two types of elements: one form element and one or more input elements. The <input> element is used to create a variety of different types of input fields for form users to interact with.

Common <input type=""> Values

The input element is a very flexible element who appearance and behavior can change dramatically based on the type attribute applied to the element. The most common type values include: text: The default value for the type="" attribute. Defines a single line of text 20 characters wide. The width can be adjusted with the size attribute as you can see in the form code in our previous example. password: The password type is basically the same as the text field with the exception that characters entered into a password field are masked. radio: Radio buttons can be used to provide multiple options of which only one may be chosen. checkbox: Checkboxes are similar to radio buttons, but more than one selection can be active at a time. This means multiple values can be submitted with a set of checkboxes while a set of radio buttons will only accept one value. submit: The submit type value creates a form submission button. When clicked, the form will take the action specified in the action attribute associated with the form element. Many forms make use of just one or two input types, and most simple forms are built using just the types listed above. However, there are many additional types you can use to accept form data that doesn't fit into any of the types listed above.

Less Common <input type=""> Values

These input types are less common than those listed above but are supported by virtually all browsers and can be used to build many different types of form inputs. button: If you want to run a script when a button is clicked, the button input type can be used to create a button which can be associated with a variety of actions. hidden: This attribute type is usually used simultaneously with the value attribute, which we'll cover momentarily, to add a pre-defined value to every form submission. For example, if you have contact forms on five different pages you could add <input type="hidden" value="page_name"> to each form to submit the name of the page where the contact form was submitted from. reset: This type is used to create a reset button that will return all form fields to their default state. file: If you want to allow form users to upload and submit files, <input type="file"> will provide that capability. image: In the past, it was common to use an image as a submit button. While this type value is still valid, it is not used very frequently in modern web form design. Instead, use CSS to style the button.

New <input type=""> Values Added by HTML5

Several additional input types are defined by the HTML5 specification. Many of these types have limited browser support. So if you use them, be sure to check caniuse.com for browser support and provide adequate fallback options where appropriate. search: This is the proper type to specify if your form provides search functionality. Unlike most of the other types of inputs added in HTML5, type="search" is supported by all browsers. Just remember that this feature doesn't actually provide search functionality, it just creates a form input field designed to be used as a part of a search feature. color: When this input type is specified it will display a colored-button that launches a basic color selector tool. Set the default color value by using the value attribute and a hex color code like this: <input type="color" value="#0000FF">. number: This type produces a field for entering a number which has increment buttons on the righthand side of box. Limits can be placed on the range of acceptable entries with the max, min, and step attributes, but browsers that lack support for this element typically fallback to a standard text input that does not recognize these limits. range: Browser support for this element is pretty good with a few exceptions. Use this attribute to produce a slider which can be used to select a value within a specified range. For example, this code would produce a slider to select a number between 100 and 1000 in increments of 50: <input type="range" name="range" min="100" max="1000" step="50">. You'll need to pair the range element with another technique to provide a live preview of the selected value. Thankfully, HTML5 Doctor has a simple way to do this using the output element. Date and Time Types: HTML5 added a number of input types that can be used to specify time and date values. For example, the date type defines a control to enter a year, month, and day. To add time to the date input, use datetime-local. If you want time without date information use the time input type. Less specific input types include the month and week options which can be used to select a week or month within a year without specifying the day or time. Browsers have been slow to add support for this type, so be sure to check for browser support and provide fallbacks if you use this type of input. Contact Detail Types: Broad support is available for the three input types used to collect pertinent details like email addresses (email), telephone numbers (tel), and website URLs (url).

Common Input Attributes

While the type attribute is by far the most-used and most useful input attribute, there are several other attributes you will need to know to build useful forms. name: The name assigned to an input element will be submitted along with the value entered into the associated field. In other words, if the value "Fred" were entered into an input element with this code <input type="text" name="first_name"> the value submitted would be "first_name=Fred". value: The value of an input element performs a different function depending on the type of input it is applied to. When applied to the submit, reset, or button types the value is used as the text on the button. When applied to text fields it provides the default value associated with the field. When associated with a checkbox or radio button, the value provides the value that will be associated with that field if selected.

<!--Will produce a button with the label "Send Now"--> <input type="submit" value="Send Now"> <!--Will produce a text field with "Google" preloaded in the field--> <!--Use when you know the value that should be submitted, not as placeholder--> <p>Who referred you to our website?:<br> <input type="text" name="Referrer" value="Google"></p> <!--If a radio button is selected the value "color=pink" or "color=red" will be submitted--> <p>Pink: <input type="radio" name="color" value="pink"></p> <p>Red: <input type="radio" name="color" value="red"></p> 

readonly: When readonly is applied as an attribute of an input element the value in the field cannot be changed. JavaScript can be used to remove the readonly attribute after some other action is taken, such as clicking a button or selecting a checkbox. For example, readonly could be applied to a submit input type and removed when a checkbox was selected confirming that the user accepted the website's terms of service. disabled: We used this attribute with example form embedded earlier in this tutorial. Use this attribute to disable an entire form, fieldset, a single field. size: Use the size attribute with text input types to specify the visible width of the field without limiting the number of characters that may be entered into the field. maxlength: If you don't want to accept more than a certain number of characters in a given field, use maxlength to limit those fields to a defined number of characters. checked: If you want a checkbox or radio button to be preselected when a form loads apply this attribute to that input element. These attributes have broad support and are used commonly with forms you encounter every day.

New Attributes Added by HTML5

HTML5 added many new attributes which can be associated with input elements. Browser support for some of these elements is limited, so be sure to check for support and provide fallback options for users of unsupported browsers. autocomplete: If your form includes common fields, leaving autocomplete on will allow the visitors browser to suggest entries based on previously completed forms. autofocus: Use this attribute to identify the form field that should be in focus when the form loads. multiple: The multiple attribute can be used with email and file input types to allow form users to input more than one value. When used for email inputs, more than one email address can be submitted by separating each address from the next with a comma. When used for file inputs, multiple files may be selected and submitted simultaneously. pattern: There may be times when you want to specify that the value of an input must meet certain criteria. For example, you may want to require that a password field includes at least one uppercase letter, one lowercase letter, one number, and meets a minimum length requirement. The pattern attribute can be used to create expressions against which input values are validated. Writing these expressions, referred to as Regular Expressions or RegExp, is beyond the scope of this tutorial. You can learn about regular expressions at Wikipedia and then write and test your expressions for free at RegExr. placeholder: Most forms include placeholder text which disappears as soon as you click into the field or begin typing. Use this attribute to add and define placeholder text for any inputs that accept text. required: If certain fields in a form are required, use this attribute to prevent submission of incomplete forms. form: If you ever need to place an input element outside of the form element, you can associate the displaced element by using the form attribute and applying a value that matches the id attribute applied to the form. Modify Form Submit Button Behavior There are five attributes that can be applied to submit and image input types to override the attributes applied to the parent form element. These attributes include:

  • formaction: Define a different URL from the one identified in the parent form's action attribute to process a form submission. Often used when forms may be processed in more than one way to provide a variety of form submission options.
  • formenctype: Specify an encoding type that should be used for form submissions. The value used overrides the value applied to the enctype attribute of the parent form element.
  • formmethod: This attribute is used specify either the get or post method value and will override the method attribute applied to the parent form.
  • formnovalidate: If you don't want form input to be validated when submitted you can use this attribute.
  • formtarget: Override the target attribute applied to the parent form element by applying this attribute to a submit or image input type field.

Define the Size of type="image": If you use the image input type to create a form submission button, you can control the size of the image using the height and width attributes. Alternatively, you can do the same thing with CSS. Most developers and designers would recommend avoiding these attributes and controlling button appearance with CSS. Set Limits and Increments for Numeric Values: You can use the min, max, and step attributes to define minimum and maximum values as well as acceptable increments falling between these values for any input that accepts numeric values.

Drop-Downs, Text Areas, & Buttons

Inputs aren't the only elements that can be used to create form fields. Other types of elements can be associated with forms to create drop-down lists or options, free-form text areas, and flexible buttons.

Pre-Populated Drop-Down Lists

To create a drop-down list of pre-populated options from which a website visitor can select an option, use the select element to create the field, and nest multiple option elements to create the various options that should appear in the drop-down menu. For example, to create a drop-down menu of pretentious color options for a fictional e-commerce store, the following code could be used:

<select name="color">   <option value="tan">Windswept Sand Dune</option>   <option value="green">Lush Forest</option>   <option value="blue">Turbulent Waters</option>   <option value="black">Deep Night</option> </select> 

Note that the value is what will actually be submitted with the form while the text between the opening and closing tags is what is presented to the visitor completing the form. For example, if a visitor selects "Lush Forest" the actual value submitted with the form will be green. Here's how our drop-down list shows up in the browser:

Free Form Text Areas

All of the text inputs we've seen so far, such as <input type="text">, only accept a single line of text. However, if you want to create a larger text area for longer text input a single line input field isn't going to work. The textarea element is the correct choice for creating a large text input area capable of accepting text input that won't render well on a single line. There are three parts to a textarea:

  1. The textarea is created by inserting opening and closing tags. Any text nested between the tags will be loaded in the text area when the form loads and will be submitted along with the form unless the visitor submitting the form deletes the text out of the textarea.
  2. If you want to define the size of the text area use the rows attribute to define the number of rows of text that should able to be displayed without resizing the text area.
  3. To set a predefined width use the cols attribute. The value applied will be the number of characters that will appear on a single row before wrapping to the second row.

Text area elements are resizable. However, the rows and cols attributes will define the size of the textarea when it is first rendered by the browser and will also set the minimum space the area may be resized to fit.

<textarea rows="3" cols="60" placeholder="Enter Text Here"> </textarea> <br> <textarea rows="3" cols="60">   Enter Text Here </textarea> 

This code will produce two identically sized text areas that are three rows tall and can accept 60 characters per row. They will be resizable to any size larger than the default size. Note how the placeholder text was added to the first with the placeholder element but simply nested between the opening and closing tags in the second example. Below you can see how these two bits of code are rendered.

While textarea size can be specified using 'rows' and 'cols', it is a better practice to use CSS to style and size text areas. Many of the attributes that can be applied to input elements can also be applied to textarea elements. In addition, to those included in our example above, attributes that can be applied to text areas include: autofocus, disabled, form, maxlength, name, readonly, required, and wrap.

Flexible Buttons

There are two ways to create buttons for forms:

  • <input type="button/submit/reset/image">
  • <button type="button/submit/reset/"></button>

We've already talked about the input element and the different types that can be used to create buttons. So why is there another button? There are least two ways that button elements are different from their input cousins.

  1. Because buttons are made with an opening and closing tag, different types of content – usually text and images – can be nested between the opening and closing tags and will be rendered on the button.
  2. Buttons do not have to be associated with a form element. They can be used as standalone buttons to initiate scripts, as the content of an anchor element, and to perform other actions.

Form Elements Added in HTML5

Three new form elements were added in HTML5: datalist: Use this element to provide a list of suggested autocompletion values for an input element. In order to use the datalist element, first create an input element with a list attribute. Then create a datalist element with an id attribute. The value applied to the input list attribute must match the datalist id. Values are added to the datalist by adding option elements between the opening and closing datalist tags. Here's an example of how this all works:

<p>What is your favorite web technology?</p> <input type="text" list="web_technologies" name="web_technology"> <datalist id="web_technologies">   <option value="HTML">   <option value="CSS">   <option value="JavaScript">   <option value="jQuery">   <option value="PHP">   <option value="Bootstrap"> </datalist> 

When we render that code in the browser and input element will appear. If we begin typing, autocomplete suggestions will be made based on the options included in the datalist. Note that users submitting the form aren't limited to selecting from one of these options. They can still choose to type a value that is not an included option if they wish to do so.

What is your favorite web technology?

output: Use this element to display the result of a calculation or user input. Associate it with an input element by using the for attribute with a value that matches the id of the relevant input element, or associate it with a form by adding a form attribute using a value that matches the id of the relevant form. The output element can also be paired with the range element to let form users know the exact value represented by the current position of the slider of a range element. Using the output and range elements in this way is beyond the scope of this introductory tutorial, but if you want to use these two elements together you can learn more about this technique at the HTML5 Doctor.

Next Steps

This tutorial has provided an overview of the elements used to build forms for the web. The next step is to try out some of the knowledge you've gained. Other tutorials in this section will walk you through the process of creating a reservation form, styling and designing forms, and ensuring that your forms meet usability and accessibility guidelines.

Frequently Asked Questions

How do you restrict a form field to only accept numbers?

In the past, restricting a field to numbers only required the use of JavaScript. However, with the release of HTML5, it's now simple to limit a field to numeric input only. Just apply the number value to the type attribute of the applicable input element. For example:

<input type="number"> 

When rendered, produces a text input field that will only accept numbers.

How do you restrict a form field to only accept alphanumeric characters?

In the past, the only way to limit field input to alphanumeric characters was to use jQuery or JavaScript and craft a custom function. However, HTML5 added the pattern attribute for input elements which can be used to restrict a form field to accept alphanumeric input only. Here's the code that will do the trick:

<form>   <input type="text" pattern="[a-zA-Z0-9]{5,8}" title="Type 5 to 8 alphanumeric characters">   <input type="submit"> </form> 

In this case, the pattern element will accept lowercase letters, uppercase letters, and numbers. The second part of the value in curly braces stipulates how many total characters may be entered into the field. Let's see how that looks in the browser.

The way it works is that when you attempt to submit values that don't meet the specified pattern the title attribute is displayed. So you should put some instructions inside the pattern attribute so that users can figure out what they've done wrong. Browser support for this relatively new attribute is really pretty good. IE 9 and earlier versions of IE don't support it and Opera Mini also lacks support. However, all other browsers do support the attribute.

How do you make a form submit when the user presses enter?

If you've come across a form that does not submit when you press enter, then someone has intentionally designed the form to behave that way – and they really shouldn't have done that. Web accessibility specs are clear: design forms to allow implicit submission. What is implicit submission? Submitting a form by pressing enter. Browsers are designed to support implicit submission. Here's how it works. Take this form for instance:

<form>   <label for="name">Name: </label><input type="text" name="name"><br>   <label for="age">Age: <input type="text" name="age"><br>   <input type="submit"> </form> 

If you were focused on any element in that form and pressed enter, the form would be submitted. This is implicit submission and all modern browsers support this behavior. Use the button element in the form and you don't even have to use the submit value for the type attribute. Hit enter while focused on any element in this form and the form will still be submitted.

<form>   <label for="name">Name: </label><input type="text" name="name"><br>   <label for="age">Age: <input type="text" name="age"><br>   <button>Submit</button> </form> 

So how do developers break this behavior? One way to get around this behavior–and to be clear, we don't recommend this–is to drop the form elements. The browser knows what to submit by grouping together everything between the form tags. Drop those tags and the browser doesn't know what to submit. Another way some developers manipulate browser behavior is to use CSS to make buttons rather than proper HTML elements, like this.

<style> .submitButton {   padding: 10px 20px;   margin-top: 10px;   background-color: #ddd;   border-radius: 5px;   display: inline-block; } .submitButton:hover {   background-color: #ccc; } .submitButton:active {   background-color: #ddd; } </style> <form>   <label for="name">Name: </label><input type="text" name="name"><br>   <label for="age">Age: <input type="text" name="age"><br>   <span class="submitButton">Submit</span> </form> 

Which, when rendered by the browser, would produce a button that looked like a button but did not do anything when enter is pressed.

Usually, developers have good intentions when they do things like this. Typically, what they're trying to do is tie form validation to an onClick JavaScript event. Form validation is a good thing, but creating a barrier to accessibility in the name of form validation is not a good thing. So, what should you do instead of disabling implicit submission? Leave implicit submission intact and use JavaScript to add an event listener to each field. Use the event listener to trigger form validation like this.

document.getElementById('name').addEventListener('keypress', function(event) {   if (event.keyCode == 13) {     /* Run Form Validation JavaScript */   } }; 

That code leaves implicit submission intact, but still runs validation code when the user presses enter.