Logotipo horizontal de Diego C Martín colores invertidos, blanco y naranja para findo negro

All about HTML forms with examples

Categorías:  Autor: Diego C Martin 
img-2

In this article we will see everything you need to create forms in HTML and in the final part you will find the new controls and elements for forms that HTML5 incorporates.

HTML Form Basics

A form is used to obtain data that the user of the web enters.

It is a means to get feedback on the site, sell products or services, collect information, etc., in an orderly and structured way.

Examples of forms would be from the typical contact forms of any web page, to the shopping cart of a virtual store or the process of buying airline tickets.

How to make an HTML form

Let’s see the basic syntax to create a form where the name, surname and age are requested.

To create a form we must use the form tag, which has a start and end clause. Within the form label we will use other elements to create buttons, text fields, check boxes, radio buttons, etc.

To begin with, in the opening of the form tag we must define the action and method attributes:

<form action="data.php" method="post">

Method can store only two values, post or get, which define the method of sending the information entered by the user.

Normally a form is sent by post, with which the data is sent with the body of the form.

In case of using get, the data is sent in the header of the request of the page. Using the get method we are limited in the amount of data to be sent, but not with the post method.

The action property is a URL that indicates the server or file to which information will be sent.

At this point we must bear in mind that HTML is simply concerned with “painting” the form on the web. It will be a programming language like PHP that deals with the processing of the data that is sent.

Now let’s see the text box where the name is entered:

Name:<br>
<input type="text" name="name" id="nombre" value="John">

The message “Name:” is a fixed text to which we add a line break to make the text box appear on the next line.

The input tag allows you to define a text box if we assign the type property the value “text”.

Every text box must use the name attribute with a name for the text box. This will be a fundamental data to be able to recover the data once the form is sent to the server, for example, using PHP.

The value attribute is displaying preloaded text in the text box, which the user can modify.

We can also use the placeholder attribute to indicate a help value that appears in a faint color and automatically disappears once the user starts typing in the text box.

<input type="text" name="name" id="name" placeholder="John">

Buttons of an HTML form – input type=”button”

We can create buttons using the input element by assigning the value “button” in the type attribute.

Although we can’t make it work without a programming language like JavaScript, we can create a page that displays it.

Example of HTML calculator with form:

Additionally, by modifying the value of the type attribute, we can make use of other types of buttons.

file : The user will be able to select a file to attach to the form.

submit : Used to send the form data to the server. With the value attribute we define the text of the button.

image : Button that looks like the image defined by the src attribute. The functionality is the same as submit.

reset : to clean the form data.

<head>
<title>Form buttons</title>
<meta charset="utf-8">
</head>
<body>
<div id="container">
<h2 id="header">Form buttons</h2>
<form id="form1" name="form1" method="post"
          action="data.php">
Button type button:<br>
<input type="button" name="btn_generico"
                  id="btn_generico" value="Accept"><br><br>
Button type file:<br>
<input type="file" name="btn_file"
                  id="btn_file"><br><br>
Button typeimage:<br>
<input type="image" name="btn_image"
                  id="btn_imagen" src="images/ok.png"><br><br>
reset type button:<br>
<input type="reset" name="btn_reset"
                  id="btn_reset" value="Clear form"><br><br>
Button type submit:<br>
<input type="submit" name="btn_submit"
                  id="btn_submit" value="Submit"><br><br>
</form>
</div>
</body>
</html>

There is another value that we can use in the type attribute of the input tag that is called hidden and that serves to store data without being shown to the user (hidden). has the attributes name and value:

<input type="hidden" name="hidden_field" value="Xx">

This field makes sense, for example, if we perform a calculation with a programming language such as JS and we want to save it to be sent next to the form, but not to be shown to the user.

Password box in HTML form – input type=”password”

We can create a field for password entry using input with the password value in the type attribute.

<html>
<head>
<title>Form Test</title>
</head>
<body>
<form action="data.php" method="post">
Name:
<input type="text" name="name" size="20">
<br>
Password:
<input type="password" name="key" size="12">
<br>
<input type="submit" value="Submit">
<input type="reset" value="Clear">
</form>
</body>
</html>

The new syntax for defining a text box for the password:

<input type="password" name="key" size="12">

We use the same input element, but we initialize the type property with the value “password”, with this we achieve that when the visitor enters the password, asterisks are displayed instead of the characters.

input type=”reset” to clean the form

To define a button that allows you to delete all the data entered so far in the HTML form:

<input type="reset" value="delete">

Another issue to keep in mind is that the name property of each input element must be unique.

We also see in the example above that a size is specified to the inputs. This is the number of characters they can accept and the predefined value is 20, although in reality it is not used too much since through CSS we can comfortably modify the size in other ways.

Text areas in forms for the user to tell you their penalties

The textarea element allows the input of several lines of text unlike the text box.

The example below specifies a size and initial text, but neither is mandatory at all.

<html>
<head>
<title>Text area</title>
<meta charset="utf-8">
</head>
<body>
<div id="container">
<form id="form1" name="form1"
          method="post" action="data.php">
<h3>text area</h3>
<textarea rows="14" cols="50">This is a
          preloaded text inside text area
</textarea>
</form>
</div>
</body>
</html>

As you can see, the syntax for defining a text area is different. In this case we do not use an input, it is another label that requires a start and end clause.

With the rows and cols attributes , you are assigned rows and columns of space to write.

Check boxes in HTML forms – input type=”checkbox”

Checkbox is another form control used to include check boxes that can take two values, selected or unselected.

<html>
<head>
<title>Form Test</title>
</head>
<body>
<form action="data.php" method="post">
Enter your name:
<input type="text" name="name" size="30"><br>
Select the languages you know:
<br>
<input type="checkbox" name="java">Java<br>
<input type="checkbox" name="cmasmas">C++<br>
<input type="checkbox" name="c">C<br>
<input type="checkbox" name="csharp">C#<br>
<input type="submit" value="Submit">
</form>
</body>
</html>

As you can see, if we want a message to appear next to the checkbox we add it after the input.

Radio buttons on the form – input type=”radio”

We use it when we have a set of options, but only one can be selected.

To create it we also use the input element initializing type with the value “radius“:

<html>
<head>
<title>Form Test</title>
</head>
<body>
<form action="data.php" method="post">
Enter your name:
<input type="text" name="name" size="30"><br>
Select the highest level of education you have:
<br>
<input type="radio" name="studies" value="1">No
studies<br>
<input type="radio" name="studies" value="2">Primary<br>
<input type="radio" name="studies" value="3">Secondary<br>
<input type="radio" name="studies" value="4">University<br>
<input type="submit" value="Submit">
</form>
</body>
</html>

As we can see, they all have the same value in the name property. With this it is achieved that when we select one, the previously selected one is deselected, so that only one is selected.

The value that is sent to the server is the data stored in the value property.

If we want to have several input groups of this type, we must define the name property with different names for each group.

Drop-down lists on forms – select

Allows the user to select one or more values from a drop-down list:

As you can see it is a label with an opening and closing clause that contains the options in the list in another option tag.

Let’s see the attributes that appear:

name : name of the list, essential to refer to the list.

disabled : to disable the functionality of the list, just like in text boxes.

multiple —Select multiple values from the list.

size : Typically used in conjunction with multiple to directly display all displayed options. By default it has the value 1.

We can also group options with the label and its respective closing clause within select to create subgroups:

Html form section grouping and tags

There are form labels that allow us to organize and rank your information: label, fieldset and legend.

Label: allows us to associate a title with an element of the form. We usually use it with text boxes, text areas, and drop-down lists. It has the attribute for, in which we indicate the id of the referenced element.

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

When the user clicks on the label, it is as if they are clicking on the element.

Fieldset aims to contain and edge a set of controls on a form.

We must enclose all the controls to be grouped between the opening and closing <labels fieldset> and </fieldset> respectively. In addition, to add a title to this box we can add another HTML element called legend.

<!DOCTYPE html>
<html>
<head>
<title>Survey</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<body>
<div id="container">
<h2 id="header">Cinema Quiz</h2>
<form id="form1" name="form1" method="post" action="data.php">
   <fieldset id="personal_data">
<legend>Personal data</legend>
<label for="name">Name:</label><br>
<input type="text" name="name" id="name"><br>
<label for="surnames">Surnames:</label><br>
<input type="text" name="surnames" id="surnames"><br>
<label for="dni">DNI:</label><br>
<input type="text" name="dni" id="dni" maxlength="9"><br>
<label for="age">Age:</label><br>
<input type="text" name="age" id="age" size="2" maxlength="2"><br>
<label for="sex">Sex:</label><br>
<select id="sex" name="sex">
<option value="X" selected="selected">...</option>
<option value="M">Male</option>
<option value="F">Female</option>
</select>
</fieldset>
<fieldset id="best_movie">
<legend>Best Film</legend>
<input type="radio" name="movie" value="1">The Godfather<br>
<input type="radio" name="movie" value="2" checked="checked">Twilight<br>
<input type="radio" name="movie" value="3">The Hateful 8<br>
<input type="radio" name="movie" value="4">Anatomy of a Murder
</fieldset>
<fieldset id="opinion_group">
<legend>Your opinion</legend>
<textarea id="opinion" name="opinion" rows="10" cols="50"></textarea>
</fieldset>
<br>
<input type="reset" value="Delete form">    <input type="submit" value="Submit">
   </form>
</div>
</body>
</html>

New controls and form elements in HTML5

New HTML5 form controls

In HTML5 we have new form controls for the input tag, that is, to use them we must use them as the value of the type attribute:

color : To select a color from a color palette.

<input type="color" name="choosecolor">

datetime : as date but including time and time zone.

datetime-local : like the previous one but without time zone. This one is more pleasant to use for the user than the previous one, since a calendar appears to select the date.

email : specific text field for email that also automatically validates the structure.

month : as date, but to select months.

number : specific text field for numbers that also validates automatically. Additionally, we can add the min and max attributes to allow only the input of values within the range.

<input type="number" min="1" max="5" name="numbers">

search : for search boxes.

tel : for telephone numbers.

time : for time selection.

url : to enter URL. Validates automatically.

week : to choose weeks within a calendar.

New tags for HTML5 forms

<datalist>

New item to create text boxes with autocomplete. It works similar to select, except that we will enter the available options through the option tag and a value attribute to indicate the option.

<form name="form" action="data.php" method="post">
   <input type="text" list="movies">
   <datalist id="movies">
     <option value="Gone with the Wind">
     <option value="King Kong">
     <option value="George of the Jungle">
     <option value="4 weddings and a funeral">
   </datalist>
</form>

On this CSS Tricks page you can see some combinations with datalist and other input. (Español).

And here a list with the Spanish provinces in the form of a drop-down list with select, but we can easily transform it into a datalist and use the autocomplete function.

<keygen>

It is used to send data with encryption and generate secure connections with the server. The field displays a drop-down list to select the degree of encryption of the data.

<keygen name="encrypted">

<output>

Displays the result of a mathematical operation specified in a script that is specified in the oninput attribute. It doesn’t make much sense without using JavaScript.

<form oninput="sum.value= parseInt(field1.value) + parseInt(field2.value)">
<input type="number" id="field1" value="">
+
<input type="number" id="field2" value="">
<output name="sum" for="field1 field2"></output>
</form>

Validation

We have already seen some introductory fields that involve validation. For example, email or url will make sure that we respectively enter a grammatically correct email or url. Let’s look at additional techniques with which to ensure the integrity of our forms:

First, we can make entering data in a field mandatory with the required attribute.

We can use it as a normal attribute or with abbreviated syntax.

<input type="text" required="required">
<input type="text" required>

We can also prevent or allow values using regular expressions in the pattern attribute.

If, for example, we want to store vehicle license plates, we could specify the following:

<input type="text" pattern:"[0-9] {4} - [A-Z] {3}">

The above expression specifies that 4 numbers, a hyphen – and three capital letters must be entered. If not, the browser will display an error.

Learn more in W3 Schools and typical expressions in HTML5 Pattern.

More about regular expressions.

Highlight, autocomplete, and prevent copying into HTML forms

With the autofocus attribute we can highlight the initial field by which the user should start filling out the form. We can use it in abbreviated mode and it is not recommended to use it more than once per page:

<input type="text" autofocus>

By default, navagadores usually use the autocomplete attribute with the value on. autocomplete=”on”. This is used for the user to see a list of values previously entered in fields with the same name. We can deactivate it with the value off.

We can also prevent copying and pasting the clipboard using the attributes:

oncopy="return false" onpaste="return false"
<input type="text" oncopy="return false" onpaste="return false">

You can see examples of form styling with CSS here.

Leave a Reply

Your email address will not be published. Required fields are marked *

Artículos de la misma categoría

crossmenu
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram