Forms
HTML documents can use forms to send data back to a server.
A form is introduced using the form element. This has two important
attributes: action and method.
The action attribute provides a URL to server-side code that will process
the form data. The method attribute specifies which HTTP method will
be used to submit the data to the given URL. This defaults to GET, but you
can use POST instead. We discuss the difference between these two options
later.
Here’s a small example:
This has a single form field, implemented using the input element,
tailored to the input of email addresses. This element’s name attribute
is used to provide a name for the data that the user types into the field.
The field is described using a label element. Notice how the for
attribute is used to associate the label with the form field that it describes.
The value of the label’s for attribute has to match the value of the
associated form field’s id attribute.
The form also includes an input element of type submit. This produces
a button that can be clicked to submit the form data to the specified URL.
You can use the value attribute to specify different button text.
As an alternative to <input type="submit">, you can use
<button>Submit</button>
Form Fields
Form fields that involve the input of a single line of text can be produced
using an input element with different values for the type attribute.
Besides email, which we saw above, you can use tel for the input of
telephone numbers, url for the input of URLs, number for numeric input
(either integer or floating point), etc.
Note that browsers will do some client-side validation of form input,
depending on the value chosen for the type attribute. For example, when
type is set to email, the browser will require that the input has two
parts separated by @.
Keep in mind that client-side validation is a usability feature, NOT a security feature!
It is trivial to bypass—e.g., by using a tool such as httpx to send
arbitrary data to the URL specified in the form’s action attribute.
For input of larger amounts of text, you can use a textarea element.
For selection of an item from a list of options, you can use the
select and option elements. Here’s a simple example:
Further Reading
MDN has an extensive collection of articles on creating forms.