• 20 heures
  • Facile

Ce cours est visible gratuitement en ligne.

Vous pouvez obtenir un certificat de réussite à l'issue de ce cours.

Vous pouvez être accompagné et mentoré par un professeur particulier par visioconférence sur ce cours.

J'ai tout compris !

Forms

Connectez-vous ou inscrivez-vous gratuitement pour bénéficier de toutes les fonctionnalités de ce cours !

Any HTML page can be enhanced with interactive forms that prompt visitors to fill in information: enter text, select options, confirm with a button... anything is possible!

However, we are reaching the limits of the HTML language as you then have to analyze the information that the visitor has entered... and this can't be done in HTML. As we're going to see, the results have to be processed in another language, such as PHP, for example.

In the meantime, we have a large number of new HTML tags to discover. Welcome to the wonderful world of forms. A world where buttons, checkboxes and drop-down lists coexist harmoniously (well almost).

Creating a form

When you have the sudden urge to insert a form in your HTML page, you need to start by writing a<form> </form>tag. This is the form's main tag and it specifies its start and end.

<p>Text before the form</p>

<form>
   <p>Text inside the form</p>
</form>

<p>Text after the form</p>

So much for basic structure. Now, pay attention: what I'm going to tell you isn't easy as we've reached the limits of HTML.

Let's take an example to make things clear. Suppose your visitor has just entered a comment in your form, such as, for example, a message that they'd like to publish in your forums. This message has to be sent so that you can receive it (logical, right?) and display it to your other visitors.

Well, that's the problem, or rather those are the problems, we're going to address:

  • Problem No 1: how do you submit the text entered by the visitor? By what means?

  • Problem No 2: once the data have been sent, how do you process them? do you want to receive the message automatically by e-mail or would you prefer a program to save it somewhere, and then display it in a page that everyone can see?

To provide the solutions to these two problems, you have to add two attributes to the<form>tag:

  • method: this attribute specifies the means by which the data are going to be sent (solution to problem No 1). There are two ways to submit data to the Web:

    • method="get": this is a method that is generally not well suited as it's limited to 255 characters. The particularity comes from the fact that the information will be sent to the page address (http://…), although this detail doesn't really matter for the time being. I recommend you use the other method most of the time:post.

    • method="post": it's the most widely used method for forms as it allows a lot of information to be sent. The data entered in the form don't go through the address bar.

  • action: is the address of the page or program that is going to process the information (solution to problem No 2). This page will send you an e-mail with the message if this is what you want, or else save the message with all other messages in a database.
    This can't be done in HTML and CSS so we generally use another language that you may have heard about: PHP.

So we're now going to complete the<form>tag with two attributes that we've just seen.

Formethod, you've guessed it, I'm going to enter the valuepost.
Foraction, I'm going to enter the name of a fictitious page in PHP (traitement.php). This is the page that will be called when the visitor clicks on the submit button in the form.

<p>Text before the form</p>

<form method="post" action="target.php">
   <p>Text inside the form</p>
</form>

<p>Text after the form</p>

For the time being, we don't know what happens inside the pagetarget.php: let's take my word for it and assume that this page is up and running.

Our priority, for the time being, is to find out in HTML/CSS how to insert text fields, buttons and checkboxes in our web page. And this is what we're going to see now.

Basic entry fields

So, let's get back to something tangible.

We're going to review the various HTML tags needed to enter text in a form.
You should know that there are two different text fields:

  • The single-line text field: as its name suggests, you can only enter a single line into it. It's used to enter short texts, such as a user name.

  • The multi-line text field: this text field allows you to enter a large amount of text on several lines, for example, a dissertation on the use of HTML in the development of countries of South-East Asia (just a suggestion, eh... ).

Single-line text field

The figure below shows what a single-line text field looks like.

A single-line text field
A single-line text field

To insert a text field in a line, we're going to use the tag<input />.

To create a single-line text field, you have to enter:

<input type="text" />

This is still not enough: you have to give your text field a name. Although this name doesn't appear on the page, you'll need it later. Indeed, it'll tell you (in PHP, for instance) where the information comes from: you'll know that such and such a text is the visitor's user name, such and such a text is the password they've chosen, etc.

To give a name to a form item, you use the attributename. Here, we're going to assume that the visitor is asked to re-enter their user name:

<input type="text" name="pseudo" />

So let's try to create a very basic form with our text field:

<form method="post" action="target.php">
   <p><input type="text" name="username" /></p>
</form>

As usual, I strongly suggest you try this code yourself to see the result.

Labels

This text field is all very well but if your visitor comes across it, they won't know what to enter. This is precisely the role of the<label>tag:

<form method="post" action="target.php">
    <p>
        <label>Your user name</label> : <input type="text" name="username" />
    </p>
</form>

This code gives the exact same result that you saw in the previous figure.

But this is not enough. You have to link the label to the text field.
To do this, you have to give the text field a name, not using thenameattribute but with theidattribute (that can be used with all tags).

Anameand anidin the field? Won't that be redundant?

Yes, somewhat. Personally, I givenameandidthe same value, this is not a problem.

To link the label to the field, it has to be given anforattribute which has the same value of the fieldid... It's best to see this in an example:

<form method="post" action="target.php">
   <p>
       <label for="username">Your user name</label> : <input type="text" name="username" id="username" />
   </p>
</form>

Try clicking on the "Your user name" text: you'll see that the cursor is automatically placed in the corresponding text field.

A few additional attributes

You can add a number of other attributes to the<input />tag to customize its operation:

  • You can increase the size of the field usingsize.

  • You can limit the number of characters that can be entered usingmaxlength.

  • You can pre-populate the field with a default value usingvalue.

  • You can give some indication of the field's contents usingplaceholder. This indication will disappear as soon as the visitor has clicked inside the field.

In the following example, the text field contains an indication providing an understanding of what should be entered; although the field is 30 characters long, you can't enter more than 10 characters inside:

<form method="post" action="target.php">
    <p>
        <label for="username">Your user name:</label>
        <input type="text" name="username" id="username" placeholder="Zozor" size="30" maxlength="10" />
    </p>
</form>

Test the result yourself to see how the field behaves. In the meantime, the figure below shows how the field looks in its initial state.

A text field with an indication (placeholder)

Password field

You can easily make the text field behave like a "password field", in other words, a field where you don't see on the screen the characters entered. To create this type of entry field, use the attributetype="password".

I'll fill in my form. It now prompts the visitor to enter their user name and their password:

<form method="post" action="target.php">
   <p>
       <label for="username">Your user name:</label>
       <input type="text" name="username" id="username" />
       
       <br />
       <label for="pass">Your password:</label>
       <input type="password" name="pass" id="pass" />
       
   </p>
</form>

You'll see that the password characters aren't displayed on the screen, as shown in the figure below.

A password entry field

Multi-line text field

To create a multi-line text field, you change the tag: we're going to use<textarea> </textarea>.

Like any other form item, you have to give it a name usingnameand use alabelthat explains what it is.

<form method="post" action="target.php">
   <p>
       <label for="improve">How do you think I could improve my website?</label><br />
       <textarea name="improve" id="improve"></textarea>
   </p>
</form>

And here's the result as an image (figure below)!

A small multi-line entry field
A small multi-line entry field

As you can see, it's a bit small! Fortunately, you can change the size of<textarea>in two different ways.

  • In CSS: just apply the CSS propertieswidthandheightto<textarea>.

  • With attributes: you can add the attributesrowsandcolsto the tag<textarea>. The first one specifies the number of lines of text that can be displayed simultaneously, and the second one the number of columns.

Why do you open the<textarea>tag and then close it again immediately afterwards?

You can pre-populate<textarea>with a default value. In this case, we don't use the attributevalue: we simply enter the default text between the opening tag and the closing tag!

<form method="post" action="target.php">
   <p>
       <label for="improve">
       How do you think I can improve my website?
       </label>
       <br />
       
       <textarea name="improve" id="improve" rows="10" cols="50">
       Improve your website?! 
       Come now! It's so great it won't need any improving!
       </textarea>       
   </p>
</form>

And here's the result in the figure below.

A pre-completed multi-line entry field
A pre-completed multi-line entry field

Enhanced entry fields

HTML5 provides many new features related to forms. Indeed, new field types emerged with this version. Just give thetypeattribute of the<input />tag one of the new available ​​values. Let's do a quick overview!

Email

You can prompt visitors to enter an email address:

<input type="email" />

The field will normally seem the same to you, but your browser now knows that the user has to enter an email address. It can display an indication if the address is not an email, which is what Firefox does, for example (figure below).

An incorrectly entered e-mail is framed in red in Firefox
An incorrectly entered email is framed in red in Firefox

Note that some browsers, such iPhone and Android mobile browsers for example, display a keyboard suitable for entering email addresses (below).

iPhone e-mail entry keyboard
iPhone email entry keyboard

A URL

With theurltype, you can prompt the visitor to enter an absolute address (usually starting withhttp://):

<input type="url" />

Same principle: if the field doesn't seem different on your computer, be aware that it has effectively understood that the visitor is supposed to enter an address. For example, mobile browsers display a keyboard suitable for entering URLs (figure below).

iPhone URL entry keyboard
iPhone URL entry keyboard

Phone number

This field is used for entering phone numbers:

<input type="tel" />

On the iPhone, for example, a suitable keyboard is displayed when the visitor has to fill in the field (figure below).

iPhone phone number entry keyboard
iPhone phone number entry keyboard

Number

This field is used to enter an integer:

<input type="number" />

The field is usually displayed with small arrows to change the value (figure below).

Number entry field

Number entry field

You can customize the way the field works with the following attributes:

  • min: minimum allowed value.

  • max: maximum allowed value.

  • step: this is the movement "step". If you specify a step of 2, the field will only accept 2 by 2 values (for example, 0, 2, 4, 6, etc.).

A cursor

Therangetype is used to select a number with a cursor (also called a slider), as in the figure below:

<input type="range" />

A cursor through the range type

A cursor through the range type

You can use themin,maxandstepattributes again to restrict the available values.

Color

This field allows you to enter a color:

<input type="color" />

In practice, it is not used all that much by browsers at the present time. Don't be surprised if you only see an ordinary text field.

Date

There are various types of date selection fields:

  • date: for the date (05/08/1985, for example);

  • time: for the time (13:37, for example);

  • week: for the week;

  • month: for the month;

  • datetime: for the date and time (with time zone management);

  • datetime-localfor the date and time (no time zone management).

Example:

<input type="date" />

As you can see, there's a wide choice!
At present, few browsers support this type of field except for Opera.

Search

You can create a search field like this:

<input type="search" />

The browser then decides how to display the search field. It can thus add a small magnifying glass meaning that it's a search field and to possibly store the last searches performed by the visitor.

Options

HTML provides a whole slew of options that can be used in your form. These are items that require the visitor to choose from a list of possibilities. We're going to review:

  • checkboxes;

  • options fields;

  • drop-down lists.

Checkboxes

How do you create a checkbox? Nothing could be easier! We're going to use the<input />tag, this time specifying the typecheckbox:

<input type="checkbox" name="choice" />

Add a<label>in the right position, and there you are!

<form method="post" action="target.php">
   <p>
       Check the foods you like to eat:<br />
       <input type="checkbox" name="fries" id="fries" /> <label for="fries">Fries</label><br />
       <input type="checkbox" name="hamburger" id="hamburger" /> <label for="hamburger">Hamburger</label><br />
       <input type="checkbox" name="spinach" id="spinach" /> <label for="spinach">Spinach</label><br />
       <input type="checkbox" name="oysters" id="oysters" /> <label for="oysters">Oysters</label>
   </p>
</form>

And here's the result in the figure below.

Checkboxes
Checkboxes

Don't forget to give a different name to each checkbox. Later on, this will allow you to identify the ones checked by the visitor.

Finally, remember that you can have a box checked as default using the attributechecked:

<input type="checkbox" name="choice" checked />

Options fields

The options fields allow you to choose one (and only one) option from a list of possibilities. They look somewhat like checkboxes but there is a slight additional difficulty: they have to be organized as groups. Although the options in the same group have the same (name), each option has to have a different (value).

The tag to be used is always a<input />, this time with the valueradiofor the attributetype.

The example below will make this clearer:

<form method="post" action="target.php">
   <p>
       Please indicate your age group:<br />
       <input type="radio" name="age" value="moins15" id="moins15" /> <label for="moins15">Less than 15 years old</label><br />
       <input type="radio" name="age" value="medium15-25" id="medium15-25" /> <label for="medium15-25">15-25 years old</label><br />
       <input type="radio" name="age" value="medium25-40" id="medium25-40" /> <label for="medium25-40">25-40 years old</label><br />
       <input type="radio" name="age" value="plus40" id="plus40" /> <label for="plus40">Even older than that?!</label>
   </p>
</form>

Which gives result shown in the next figure.

Radio buttons
Radio buttons

Why did you put the same name for each option? Just so that the browser knows which "group" the button belongs to.
Try removing thenameattributes and you'll see that you can then select all the options. However, this is not what we want, which is why we "link" them together by giving them the same name.

If you have two different options fields, you have to give a uniquenameto each group, like this:

<form method="post" action="target.php">
   <p>
       Please indicate your age group:<br />
       <input type="radio" name="age" value="less15" id="less15" /> <label for="less15">Less than 15 years old</label><br />
       <input type="radio" name="age" value="medium15-25" id="medium15-25" /> <label for="medium15-25">15-25 years old</label><br />
       <input type="radio" name="age" value="medium25-40" id="medium25-40" /> <label for="medium25-40">25-40 years old</label><br />
       <input type="radio" name="age" value="plus40" id="plus40" /> <label for="plus40">Even older than that?!</label>
   </p>
   <p>
       Which continent do you live on?<br />
       <input type="radio" name="continent" value="europe" id="europe" /> <label for="europe">Europe</label><br />
       <input type="radio" name="continent" value="africa" id="africa" /> <label for="africa">Africa</label><br />
       <input type="radio" name="continent" value="asia" id="asia" /> <label for="asia">Asia</label><br />
       <input type="radio" name="continent" value="america" id="america" /> <label for="america">America</label><br />
       <input type="radio" name="continent" value="australia" id="australia" /> <label for="australia">Australia</label>
   </p>
</form>

Drop-down lists

Drop-down lists are another elegant way of selecting an option from several possibilities. They work in a slightly different way. We going to use the<select> </select>tag which specifies the start and end of the drop-down list. We add thenameattribute to the tag to give a name to the list.

Then, inside the<select> </select>tag, we're going to insert several<option> </option>tags (one for each possible choice). We add avalueattribute to each of them to identify what the visitor has chosen.

Here's an example of use:

<form method="post" action="target.php">
   <p>
       <label for="country">What country do you live in?</label><br />
       <select name="country" id="country">
           <option value="unitedstates">United States</option>
           <option value="canada">Canada</option>
           <option value="unitedkingdom">United Kingdom</option>
           <option value="france">France</option>
           <option value="spain">Spain</option>
           <option value="italy">Italy</option>
           <option value="china">China</option>
           <option value="japan">Japan</option>
       </select>
   </p>
</form>

The result obtained is shown in the figure below.

A drop-down list

If you want an option to be selected as default, this time use the attributeselected:

<option value="canada" selected>Canada</option>

You can also group your options using the tag<optgroup> </optgroup>. In our example, why don't you separate country according to their continent?

<form method="post" action="target.php">
   <p>
       <label for="country">What country do you live in?</label><br />
       <select name="country" id="country">
           <optgroup label="Europe">
               <option value="unitedkingdom">United Kingdom</option>
               <option value="france">France</option>
               <option value="spain">Spain</option>
               <option value="italy">Italy</option>
           </optgroup>
           <optgroup label="America">
               <option value="unitedstates">United States</option>
               <option value="canada">Canada</option>
           </optgroup>
           <optgroup label="Asia">
               <option value="china">China</option>
               <option value="japan">Japan</option>
           </optgroup>
       </select>
   </p>
</form>

The result obtained is shown in the figure below.

Options are grouped by continent

Finalizing and submitting the form

We're almost there. It only remains for us to decorate our form with few final features (such as confirmation) and then add the form submit button.

Grouping fields

If your form has grown and has a lot of fields, it may be useful to group them within several tags<fieldset>. Each<fieldset>can contain a caption with the tag<legend>. Look at this example:

<form method="post" action="target.php">
 
   <fieldset>
       <legend>Your contact details</legend> <!-- Fieldset title --> 

       <label for="lastname">What's your last name?</label></br>
       <input type="text" name="lastname" id="lastname" /></br>

       <label for="firstname">What's your first name?</label></br>
       <input type="text" name="firstname" id="firstname" /></br>
 
       <label for="email">What's your email address?</label></br>
       <input type="email" name="email" id="email" /></br>

   </fieldset>
 
   <fieldset>
       <legend>Your wish</legend> <!-- Fieldset title -->
 
       <p>
           Make a wish that you would like to come true:</br>

           <input type="radio" name="wish" value="rich" id="rich" /> <label for="rich">Be rich</label></br>
           <input type="radio" name="wish" value="famous" id="famous" /> <label for="famous">Be famous</label></br>
           <input type="radio" name="wish" value="intelligent" id="intelligent" /> <label for="intelligent">Be <strong>even more</strong> intelligent</label></br>
           <input type="radio" name="wish" value="other" id="other" /> <label for="other">Other...</label></br>
       </p>
 
       <p>
           <label for="specs">If "Other", please specify:</label></br>
           <textarea name="specs" id="specs" cols="40" rows="4"></textarea>
       </p>
   </fieldset>
</form>

The result obtained is shown in the figure below.

The fields are grouped

Automatically selecting a field

You can automatically place the cursor in one of the fields in your form using the attributeautofocus. Once the visitor loads the page, the cursor appears in this field.

For example, to place the cursor as default in the fieldname:

<input type="text" name="firstname" id="firstname" autofocus />

Making a field mandatory

You can make a field mandatory by assigning it the attributerequired.

<input type="text" name="firstname" id="firstname" required />

The browser will then tell the visitor, if the field is empty when the form is submitted, that they are required to fill it in.

:required
{
    background-color: red;
}

The submit button

So all we have to do now is create the submit button. Here again, the<input />tag comes to our rescue It's available in four versions:

  • type="submit": the form main submit button. This is the one you'll use most often. The visitor will be taken to the page specified in the form'sactionattribute

  • type="reset": reset the form.

  • type="image": equivalent of thesubmitbutton, displayed this time as an image. Add thesrcattribute to specify the image URL.

  • type="button": generic button, which will have no effect (as default). In general, this button is handled in JavaScript to perform actions in the page. We won't use it here.

To create a submit button, we thus write for example:

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

Which gives result shown in the next figure.

A submit button
A submit button

When you click the "Submit" button, the form then takes you to the page specified in the attributeaction. Remember, we imagined a fictitious page:target.php.

The problem is that you can't create this page in HTML only. You have to learn a new language, such as PHP, to be able to "retrieve" the entered information and decide what to do with it. As it happens, I'm also writing a course on the PHP language for those who might be interested! This course will be published soon.

Summing up

  • A form is an interactive area in the page, where your visitors can enter information.

  • A form is circumscribed using the<form>tag to which two attributes have to be added:method(data submitting method) andaction(page to which the visitor is redirected after submitting the form and which processes the information).

  • Many of the form's items can be inserted using the tag<input />. The value of itstypeattribute specifies the field type to be inserted:

    • text: text field;

    • password: text field for password;

    • tel: phone number;

    • checkbox: checkbox;

    • ...

  • The<label>tag is used to enter a label. It is associated with a form field using theforattribute, which must have the same value as the form fieldid.

  • You can make a field mandatory using therequiredattribute, ensure that it is selected as default usingautofocus, and specify an indication in the field usingplaceholder

  • To retrieve what visitors have entered, the HTML language is not sufficient. You have to use a "server" language such as PHP... If you want to go further, you're going to have to learn a new language!

Exemple de certificat de réussite
Exemple de certificat de réussite