SITERAW

Forms

Any HTML page can be enhanced with interactive form that allow the visitor to fill in information, select an item amongst a menu of several available options and even click a button to send the data contained in your form to another page.

Forms are pretty much everywhere on the Internet so you might be wondering why we waited so long before introducing them.

The reason is that we have reached what we can call a "limit" of the HTML and CSS languages.

At the beginning of this tutorial I said that HTML and CSS were sufficient for creating a website, and it's true.

But I never said that you could do everything with them.

HTML and CSS are markup and style sheet languages, respectively.

They allow you to create web pages and design them as much as you want and, while they are web languages, they aren't stricto sensu programming languages.

We can create forms in HTML, we can stylize them in CSS, we can even send the data they contain to another page of our website... but we can't process that data without a server-side (back-end) programming language.

By the end of this chapter you'll understand what I mean.

But for now, let's start creating forms.

Creating a form

Before creating our form elements we first have to define the form container itself, just as we did with tables in the previous chapter.

The HTML element for delineating the start and end of a form is <form>.

Here is how you use it.

<p>A paragraph before the form.</p>

<form>
    <!-- The form itself -->
</form>

<p>A paragraph after the form.</p>

Every form control we create will be contained inside the <form> element.

But before we can move on to the actual controls, there are two important attributes we should cover.

  • method : the method by which the form data will be submitted
  • action : the page to which the form data will be submitted

The action attribute is pretty self-explanatory: it's simply the target page to which the data entered in your forms will be sent, the current URI (page) by default.

For method things get a little more complicated, as it defines the method by which the data will be sent.

Form method

There exist many types of HTTP requests: HEAD, GET, POST, PUT, etc.

Only two are relevant to HTML forms: GET and POST.

And it just so happens that get and post are the two values that can be taken by the method attribute.

Let's see how these work.

The GET method

This is the default method for sending form data.

Using the get method will send the data as URL variables, meaning it will append your page address with whatever information was entered in your form.

Have you ever seen a web address (URL) looking something like this?

http://www.siteraw.com/?name1=value&name2=value

If so, chances are high you were dealing with a GET method of data transmission.

This is perhaps the most straightforward method but it does have some inconveniences.

The most evident being the fact that any data sent will be visible in the URL.

But this can also turn into an advantage since having visible data means the result page can be bookmarked and accessed directly without having to re-submit the form (e.g. http://www.siteraw.com/search?q=html).

The POST method

This is the preferred method for most types of forms.

In this case, the form data will be appended to the body of the HTTP request, meaning that it will not be directly visible in the address bar.

In addition and unlike with the GET method, there is no limit to the amount of data you can send.

This is the method we will use.

Setting up the form

We can now adjust our form using these two attributes.

For the method attribute we will use the post value and for action we will simply enter target.html, a fictitious page to which the form data will be submitted.

As I said, we can't actually process said data with HTML and CSS alone, so we'll just pretend the Death Star page is fully operational for now.

By the power of imagination.

Here is our updated code.

<p>A paragraph before the form.</p>

<form method="post" action="target.html">
    <!-- The form itself -->
</form>

<p>A paragraph after the form.</p>

Now that we've handled the form container, let's find out how to insert text fields, checkboxes, radio buttons and more.

Here is an example of what can be achieve using HTML and CSS.

A complete form using HTML and CSS
A complete form using HTML and CSS

Want to learn how to do that? Then keep reading this chapter.

Input fields

The most common form control element is input field.

The HTML element we need is <input />, which is a standalone tag.

Remember this tag well, as we'll be using it for 90% of all form related controls. Seriously.

But having an <input /> tag alone isn't enough to produce a functional form control element.

You also need to give it a type attribute.

The form element will be different depending on the value it takes.

Single-line text field

One-line text input fields allow the visitor to enter textual information on a single line.

They are often used for names, usernames, ages or email addresses.

You've certainly already seen them, but just in case I'll show you an example of something we can create with minimal HTML code.

A basic text input field
A basic text input field

To create a single-line text input field, the value of the type property we want is text.

We can add the following inside our form container.

<input type="text" />

You can try it out and see the result for yourself.

But our text input field is not complete yet.

The way forms work is that each input contains data that is sent, once the form is submitted, to a target page (here target.html).

Each data segment is constituted of a pair: name and value.

The value is whatever the visitor enters in the field while the name is an indicator of whatever the field is supposed to represent.

It just so happens that HTML allows us to use an attribute to specify that: the name attribute.

And let's also add an id attribute, we'll see why in just a moment.

<input type="text" name="username" id="username" />

You can use the same value for both name and id, it's not a problem.

Labels

In HTML, labels are used as captions for items in a user interface.

Why are they useful?

We know that our text input field is for usernames, since we built it... but what about the actual visitor?

Shouldn't we have a way to tell him: this is the field for your username?

Luckily there is an HTML element for that: <label>.

It's an inline tag that you can place before or after your input field, and it contains whatever explanatory text you want associated with your input.

<label>Username</label> : <input type="text" name="username" id="username" />

But that isn't all labels do.

You can also link the label to the input control, meaning that whenever the visitor clicks the label text he will be focused on the control.

To do so you must add a for attribute to the <label> that matches the id attribute of the <input />.

That's why we added an id above, in case you were wondering.

Here is our completed code.

<form method="post" action="target.html">
    <p>

        <label for="username">Username</label> :

        <input type="text" name="username" id="username" />

    </p>
</form>

This code will give you the exact result you saw in the previous illustration.

Try clicking on the label to see the binding effect: your cursor should automatically be focused on the corresponding text field.

A few additional attributes

There are a few additional attributes that can be added to the <input /> element to further customize its operation.

  • minlength : specifies the minimum number of characters the user can enter
  • maxlength : specifies the maximum number of characters the user can enter (most browsers will prevent the user from typing more characters than the limit)
  • value : pre-populates the field with a chosen value
  • placeholder : somewhat similar to the above as it displays a default text inside the field, except this text isn't counted as the field's value and disappears as soon as the user focuses on the control

You can play around with these attributes to see how they work in greater detail.

Password field

Password fields are somewhat similar to regular text fields, except that you can't see whatever characters you type into the control.

To create this type of field you just need to use the password value on your type attribute.

There rest is pretty much identical to what we saw above.

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

    <p>
        <label for="password">Password</label> : <input type="password" name="password" id="password" />
    </p>
</form>

You can see the result below.

A password entry field
A password entry field

As you can see, the characters entered in the password field aren't shown on the screen.

Multi-line text field

I said that 90% of form controls involved the <input /> tag.

Multi-line text fields are an exception as we'll be using a new HTML element: <textarea>.

We well be using the same attributes as with single-line entry fields, except for type which is unnecessary.

And just like the <input /> element, <textarea> can be linked with a <label> using the same mechanism.

Let's see how it works.

<form method="post" action="target.html">
    <p><label for="siteraw">Describe the awesomeness of SiteRaw in your own words.</label></p>

    <p><textarea name="siteraw" id="siteraw"></textarea></p>
</form>

And the result.

A textarea entry field
A textarea entry field

Just as with single-line inputs, you can add as much text as you want.

The difference is that here you can hit the Enter key to produce line breaks.

You can also edit the height and width of the input field with CSS, which is what I did since the default dimensions are a bit small.

Why is there nothing inside the <textarea> tag? We just open it and close it immediately afterwards, wouldn't it have been simpler if it was a standalone tag?

That's because there is no value attribute for the <textarea> element.

If you want to pre-populate the field with a default text, you just enter your content between the opening and the closing tag.

See below.

<textarea name="siteraw" id="siteraw">Your default text.</textarea>

And the result.

A textarea with default text
A textarea with default text

The other attributes we covered, such as maxlength and placeholder, are applicable to <textarea>.

If you use CSS, you can try to match the style of both single-line and multi-line input fields.

Enhanced entry fields

In HTML5 there are many new features available related to form entry fields.

These are made available by modifying the type attribute of the <input /> element, just as we did for password fields.

Here are some of these new form control features.

Keep in mind that not all browsers will display these (relatively) new elements. But that's okay since even if the browser doesn't recognize a specific field it will show a regular single-line text input control instead.

Search field

Search fields are similar to regular text entry controls except for the fact that they are semantically marked as distinct form elements.

To turn an input control into a search field, simply use the search value.

<input type="search" />

You won't see much difference with a regular text field... until you start writing.

Some browsers will then display a small cross to the right-side of the field, allowing you to quickly clear whatever you've typed in.

A search field
A search field

Other browsers will add a small magnifying glass to distinguish the two.

Email field

The next type of input is for email addresses.

<input type="email" />

It looks, again, just like a regular text field but most browsers will check to see if the content typed inside the control matches that of an email address.

If it doesn't, it will display some sort of warning effect.

An email field
An email field

These warning effect vary from browser to browser.

In this case, as you can see in the above illustration, the field containing content that doesn't match the pattern of an email address has been automatically highlighted in red.

Mobile browsers will also display a specific keyboard for these types of entry fields, usually one containing mail-related special characters (such as @).

URL field

URL fields are very similar, they indicate that the visitor is supposed to enter a URL (website address).

<input type="url" />

As with the email field, some browsers will check to see if the content entered matches the pattern of a web address, and if not display an appropriate warning effect.

A URL field
A URL field

Same principle, mobile browsers will display a keyboard suitable for entering web addresses containing URL-specific special characters (/, .com).

Number field

This form control is used to display a numeric input field.

<input type="number" />

The field is often displayed with a set of increment and decrement arrows that allow you to change the value you entered.

You can also use your up and down keys to get the same effect.

A number field
A number field

You can also set restrictions on what numbers are accepted as well as the increment step with the following attributes.

  • min : the minimum allowed value
  • max : the maximum allowed value
  • step : the legal increment interval, by how does the value increase or decrease when using the arrows (also affects accepted values)

You can play around with these attributes to customize your number fields.

<input type="number" min="10" max="50" step="5" />

This control will accept any value between 10 and 50 by increment of 5 (i.e. 10, 15, 20, [...], 45, 50).

Remember that minimum and maximum values are included.

Range field

Range input fields, also called slider controls, are useful when you want the user to enter an approximate value.

<input type="range" />

Here is what it looks like depending on the browser you're using.

A range field
A range field

The default range is 0 to 100 with a step of 1 but those values can be adjusted using the properties we just covered: min, max and step.

Try moving the slider to the left or right to change the value of the field.

Date field

Date fields are used for input controls containing a date.

Depending on the browser, you may see a date picker similar to that of Windows' calendar.

<input type="date" />

Here is what it looks like.

A date field
A date field

This type of field demands a full date (day, month and year).

There also exist alternatives to date which only require some of those parameters: month, time, week, datetime.

Try them out.

Phone field

Finally, the phone field is used for entering a phone number.

<input type="tel" />

It doesn't amount to much visually, but on most mobile browsers the keyboard will automatically shift to numerical keys which make entering a number that much easier.

A phone field (mobile keyboard)
A phone field (mobile keyboard)

That's all for input fields, now let's cover other types of form controls.

There are two other types of input fields, hidden and file. The hidden field is, as its name implies, not visually rendered on the web page although it can be seen in the source code. It's useful for passing on data to the target page without the user having to interact with the specific form control or be otherwise involved in the transmission process. The file control simply provides a way for the user to upload a file from his computer. We won't be using any of these in this chapter, but it's always useful to know them (particularly the former).

Option controls

HTML input fields are pretty cool by themselves, and with CSS the possibilities for customization are nearly endless.

Below is just one example of what we can achieve.

A basic form with CSS
A basic form with CSS

But HTML offers much more than input fields for building your forms.

Option controls allow the user to select one or more values from a list of possibilities.

There are three methods to provide a list of option in your HTML forms.

  • checkboxes
  • radio buttons
  • drop-down menus

Let's see what they do and how they differ.

Checkboxes

Checkbox provide the user with a list of possible entries from which he can choose one or more values.

To create checkboxes in HTML we'll be once again using the <input /> element, this time specifying the checkbox type.

Don't forget to give it a name and, in case you want to attach a label to it, an id attribute.

<input type="checkbox" name="siteraw" id="siteraw" />

Each checkbox is considered an individual element in HTML, so there is no "checkbox container" like you might expect.

As such, creating a checkbox list is just a matter of adding one checkbox element after the other.

<form method="post" action="target.html">
    <p>SiteRaw is...</p>

    <p>

        <input type="checkbox" name="amazing" id="amazing" /> <label for="amazing">Amazing!</label><br />

        <input type="checkbox" name="ineffable" id="ineffable" /> <label for="ineffable">Ineffable!</label><br />

        <input type="checkbox" name="awesome" id="awesome" checked /> <label for="awesome">Awesome!</label><br />

        <input type="checkbox" name="overrated" id="overrated" disabled /> <label for="overrated">Presumptuously overrated!</label>

    </p>
</form>

And here is the result.

HTML checkboxes
HTML checkboxes

Perhaps you noticed two new attributes in our HTML code: checked and disabled.

You may also have guessed their function: to have a box be checked by default and to prevent one from being checked respectively.

We don't want people having the wrong opinions after all.

While all attributes are in theory required to have a value, this exception is permitted since HTML5. If you don't like this syntax you can always write the slightly more redundant checked="checked" and disabled="disabled", they both produce the same result. This practice is called attribute minimization and only works in certain cases when the value of the attribute is identical to its name.

Since we linked the labels to their respective checkboxes, clicking on a label will automatically check or uncheck the appropriate box.

Try it.

How do I limit the selection to only one checkbox? At the moment, I can choose more than one option!

That's the purpose of checkboxes: to allow multiple choices.

If you want to limit the selection to only one value, you should try using radio buttons.

Checkboxes and radio buttons
Checkboxes and radio buttons

That's what we'll be covering next.

Radio buttons

Radio buttons are another type of option control, which allow the user to select one - and only one - value from a list of possibilities.

To create a radio button, we'll use once again the <input /> element with the radio type.

The main difference between radio buttons and checkboxes is that while the latter were all considered distinct HTML elements, the former need to be grouped together in order to work as intended.

In practice, that means that all radio buttons of a same group will share an identical name attribute.

So how do we distinguish one option from another then?

Easy.

We simply add a value to each button.

<form method="post" action="target.html">
    <p>SiteRaw is...</p>

    <p>

       <input type="radio" name="siteraw" id="amazing" value="amazing" /> <label for="amazing">Amazing!</label><br />

       <input type="radio" name="siteraw" id="ineffable" value="ineffable" /> <label for="ineffable">Ineffable!</label><br />

       <input type="radio" name="siteraw" id="awesome" value="awesome" checked /> <label for="awesome">Awesome!</label><br />

       <input type="radio" name="siteraw" id="overrated" value="overrated" disabled /> <label for="overrated">Presumptuously overrated!</label>

   </p>
</form>

This should produce the following result.

HTML radio buttons
HTML radio buttons

As you can tell, the checked and disabled attributes also work for radio buttons.

Why do we use the same name on each option? I don't get it.

This is necessary when you want to have multiple radio buttons belonging to the same group.

If they weren't linking together via their name attribute, the browser would have no way of knowing which group each button belongs to and thus the user would be able to select more than one option... which defeats the purpose of this form control, since we already have checkboxes for that.

Checkboxes, radio buttons and CSS
Checkboxes, radio buttons and CSS

If you have more than one option field, you will want to give a unique name to each group in order to distinguish between them.

The best way to summarize: one name, one option group, different values within that group.

Remember that while more than one form control can have the same name, as we know id attributes must be unique and therefore cannot be shared by multiple HTML elements. The workaround is to match the id with the value of each control, as I did in my demonstration code.

Drop-down menus

Drop-down menus, also called select boxes or simply dropdowns, are another way of offering a selection amongst several possibilities.

Just like radio buttons, drop-down lists only permit one selection per menu.

Here is an example of what it can look like.

HTML form elements
HTML form elements

In this case, we'll need both a container element to specify the beginning and end of the list, and an option element for each item contained within the menu.

The container element is <select> and the item element is <option>.

In addition, we'll give the <select> element a name and each <option> item a distinct value.

<form method="post" action="target.html">

    <p><label for="siteraw">SiteRaw is...</label></p>

    <p>

        <select name="siteraw" id="siteraw">

            <option value="amazing">Amazing</option>

            <option value="ineffable">Ineffable</option>

            <option value="awesome" selected>Awesome</option>

            <option value="overrated" disabled>Overrated</option>

        </select>

   </p>
</form>

And the result.

HTML drop-down menu
HTML drop-down menu

The disabled attribute still works fine, but if you want an option to be selected by default it's no longer checked but selected.

Option groups

You can also group several options with the <optgroup> element.

Give it a label attribute to create a title for each group.

<select name="siteraw" id="siteraw">

    <optgroup label="Positive">

        <option value="amazing">Amazing</option>

        <option value="ineffable">Ineffable</option>

        <option value="awesome">Awesome</option>

    </optgroup>

    <optgroup label="Neutral" disabled>

        <option value="okay">Okay</option>

        <option value="overrated">Overrated</option>

    </optgroup>

</select>

You can see the result below.

Drop-down menu with option groups
Drop-down menu with option groups

Groups themselves can't be selected, they are just used to semantically categorize the items contained within the drop-down list.

You may have noticed that this time I applied the disabled attribute to the <optgroup> element rather than an individual <option> tag.

This has the effect of disabling the entire group and every item contained within.

Don't confuse the label attribute, employed exclusively with drop-down menus, and the <label> element which is used for adding a caption to a form control.

You can of course use CSS to customize your drop-down menus.

Here is an example of the type of effect you can achieve.

Drop-down menus with CSS
Drop-down menus with CSS

Don't forget that you can apply different properties to each specific element, from the container to each individual item.

Sending the form

We've covered nearly every component of HTML forms, all that's left is to add push button to confirm our data and finally send it.

But first, there are a few more useful features that we should introduce.

Field groups

Just as we can separate the items of our drop-down menus into distinct groups, so can we divide the controls of our forms into distinct fields with the <fieldset> element.

You can also add a caption for each field using the <legend> tag.

Here is an example.

<form method="post" action="target.html">

    <fieldset>
        <legend>About you</legend>

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

        <!-- Stuff -->
    </fieldset>

    <fieldset>
        <legend>About SiteRaw</legend>

        <p>Is SiteRaw awesome?</p>

        <p>
            <input type="radio" name="siteraw" value="yes" id="yes" checked /> <label for="yes">Yes</label><br />

            <input type="radio" name="siteraw" value="no" id="no" disabled /> <label for="no">No</label>
        </p>

        <!-- More stuff -->
    </fieldset>

</form>

The result obtained is shown in the figure below.

HTML fieldset element
HTML fieldset element

You can customize your field groups with CSS to make them stand out more, or less.

It's up to you.

Form specific attributes

There exist additional attributes that are employed almost exclusively with form controls and that allow you to alter either the way the form is presented, how it is processed or even the user interactions with individual elements.

We've already seen a few of them and there are still some others that we've yet to discover.

Default selection

Nothing new here, to automatically select an option we only need checked for checkboxes and radio buttons or selected for drop-down menu items.

<input type="radio" name="siteraw" value="siteraw" checked />

Disabling a field

Disabling a field is, as we saw, only a matter of adding the disabled attribute to the appropriate control.

<input type="text" name="siteraw" disabled />

Automatic focus

You can automatically place the focus on one element of your form with the autofocus attribute.

When the visitor loads the page, the affected element will automatically be focused on.

<input type="text" name="siteraw" autofocus />

Obviously, there can only be one such element per page.

Mandatory fields

You can also make a field mandatory by assigning it the required attribute.

<input type="text" name="siteraw" required />

Most modern browsers will prevent the form from being submitted if all mandatory fields aren't filled out.

In addition, a visual notification will often be provided to inform the user that a completing specific field is required.

The default visual effects themselves will vary depending on the browser but you can always use the CSS :required and :invalid pseudo-formats to apply your own.

Form buttons

Finally, the missing piece of the form puzzle: buttons.

Clickable buttons are a useful addition to your forms and all but necessary to provide a way for the user to confirm and submit the information.

Once again we will be using the <input /> element.

We'll be changing the value of the type attribute depending on what sort of button we want.

Here are the values it can take.

  • submit : sends the form data to the page specified in the form's action attribute.
  • reset : resets the value of every field contained in the form.
  • button : a generic button which will have no effect, by default. It's useful when using Javascript to perform dynamic actions on the page.

To change the text contained within the button itself, use the value attribute.

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

The result is shown below.

HTML submit button
HTML submit button

Of course, having a single submit button isn't very useful.

Let's try attaching it to a fictitious login form where the user first has to enter his username and password before submitting the form and, if the information is correct, accessing a member-only area.

Here is the demonstration HTML code.

<form method="post">

    <p>
        <input type="text" name="username" placeholder="username" required />
    </p>

    <p>
        <input type="password" name="password" placeholder="password" required />
    </p>

    <p>
        <input type="submit" name="login" value="Login" />
    </p>

    <p>Not registered? <a href="signup.html">Create an account</a></p>

</form>

You can see the result below.

HTML only login form
HTML only login form

And since we haven't done much CSS in this chapter, now is the opportunity to stylize our page a little.

The exact same code, this time with CSS.

A login form with CSS
A login form with CSS

When the user clicks the "Login" button, the data will be submitted to the target page (here it's the same page as the form, since we didn't provide an action attribute).

The problem is that you we can't do much more with HTML and CSS only, we will need a server-side programming language (such as PHP or ASP.NET) to interpret, process and manipulate said data.

There are free courses on both these languages available for free on SiteRaw, just like this one, but for now let's finish our HTML and CSS tutorial before worrying about adding another language to the mix.