Click here to Skip to main content
Click here to Skip to main content

Tagged as

Beginner's Guide to HTML5 & CSS3 - Formidable Forms with HTML5

, 26 Jan 2015 CPOL
Rate this:
Please Sign up or sign in to vote.
Getting started with HTML5 forms.

Introduction

Once upon a time, there existed countless paper forms that we had to fill up for activities like applying for jobs, opening bank accounts, admission to schools, and even registering marriages. The list went on and on. In those forms, more often than not, we would come across underscored spaces or empty boxes with labels like name and address, checkboxes with pre-defined values like "Male" and "Female", and multiple line asking for descriptive information. These forms would have to be duly completed and submitted manually by hand or by post to the organizations that supplied the forms.

We still encounter paper forms today. Thanks to web technologies, however, their usage and popularity have been quietly eroded by a new "form" of forms - the web forms. Nowadays, when we want to sign up for some activity, we will just have to visit the relevant website and fill up a web form via a browser. This web form will have a button near the bottom of the screen where we can click on it to submit the information instantly. A web form is the prevailing way for users to pass information to the server for processing. The need for web forms to go beyond the traditional usage of paper forms has enabled information exchange like social-networking, e-commerce, e-payment, and internet banking.

We have realized that web forms are the indispensable part of any website today. It is essentially an HTML document composed of the various HTML Form elements and attributes. From here on, you will embark on a journey to creating a HTML5 form.

Looking Ahead ...

At the end of the journey you will have created a "formidable form" using HTML5. (Figure 1) Click on Figure 1 to view a short video on how formidable your form will be.

Figure 1: Formidable Form with HTML5

Setting the Stage

Let's set the stage for the subsequent hands-on session. Download and extract the html5form.zip to a location on your computer, e.g. c:\html5form. You will find three files inside the extracted folder:

  • index.html
  • acknowledge.html
  • style.css

The index.html is the HTML file (shown below) in which you will add the HTML code to create the formidable form of Figure 1. Throughout the journey, you will add the code in between the comment tags of start and end.

<!DOCTYPE html>
<html>
<head>
<title>Formidable Form with HTML5</title>
</head>
<body>
    <div class="container">
        <header>
            <h1>Formidable Form with HTML5</h1>
        </header>
        <div class="form">
            <!-- start -->
           
            
            <!-- end -->
        </div>
    </div>
</body>
</html>

The acknowledge.html contains the JavaScript that will receive and echo the information submitted from index.html. In a production environment, your form data will most probably be sent to some server-side scripts for processing. However, this is beyond the scope and objective of this article.

The style.css is the external cascading style sheet that renders the look and feel of the formidable form of Figure 1. We will add this style sheet to the index.html when it is completed.

Let the journey begin ...

Getting Started with HTML4 Form

HTML4 form is the basic building block of the many web forms that we see today. An HTML4 form can contain the following data-entry elements:

  • Input elements like text fields, password fields, radio buttons, checkboxes, and submit buttons
  • textarea and drop-down lists

They together provide the UI controls for users to enter and send information to the server.

In addition, a form can also contain fieldset, legend, and label elements that provide auxiliary functions to those data-entry elements that we mentioned above.

Open the index.html on a text editor and add the HTML code as shown on the upper part of Figure 3 between the comment tags of start and end . Once you are done, save it. and launch it on a browser, and you should see the outcome as shown on the lower part of Figure 2.

Figure 2: Form and Text Fields

<form>

As shown in Figure 2, a web form starts with an opening <form> tag and a corresponding closing </form> tag. The <form> tag has been given 3 attributes as follows:

  • id contains a value, e.g. particularsform, that can be used to reference an HTML element in JavaScript and CSS.
  • action contains the url of a web page, e.g. acknowledge.html, to which the form data will be sent upon submission.
  • method is assigned the value of "get" in our example. The get method will pass form data to the receiving page by appending them as name-value pairs to the URL of the receiving page. (More on this later.) Another commonly used value for method is "post". I will stop short of going into the detail of "get" and "post" method as it is beyond the scope and objective of this article.

<input>

The <input> tag is the most important element of an HTML form. It specifies an input field within a <form> tag and a </form> tag where a user can input data. The <input> tag has no end tag.The behaviors and functions of an <input> tag is determined by the attributes that assigned to them. You will meet them in due course.

<input type="text">

The <input type="text"> tag defines a single-line text field. Between the <form> and </form>, we have added two text fields for name and email respectively in index.html.

Each of them has two attributes - the id and name. You can also set the maximum number of characters that a user is allowed to enter using maxlength attribute. We have already learned of the purpose of id. For the name attribute, its value together with the data that is entered by the user will be sent over to the receiving page as a name-value pairs. In Figure 2, for example, the name of the email text field is called "email", if someone enters "someone@gmail.com" into this email text field and submit the form, the name-value pair of email=someone@gmail.com will be sent over to the receiving page. In order to carry out this experiment, we will need the submit button. Let's fast-forward and create the submit button now.

<input type="submit">

The <input type="submit"> defines a submit button. When a user clicks the submit button, it sends the form data to a file specified in the action attribute of the <form> tag. Add the highlighted code on the upper part of Figure 3 to index.html. This will display a submit button with the "Sign up" caption as shown on the lower part of Figure 3. The "Sign up" caption is assigned through the value attribute.

Figure 3: Submit Button

You are ready to do the experiement. Enter some values into the name and email text fields respectively, click on the "Sign up" button and observe. (Figure 4)

Figure 4: Enter and Submit a Form

The values that you have entered into the respective text fields together with their respective names would have been sent over to the acknowledge.html page which is the value of the action attribute of the opening <form> tag. In our example, the acknowledge.html page will simply display the data received from index.html on the browser. (Figure 5) Note that even the submit button has also been sent over.

Figure 5: Receiving and Display Form Data

Look closer at the address bar in Figure 5, you notice that the name, email, and submit button have been appended to the url of the acknowledge.html as name-value pairs as follows: (Only the first two are shown.)

start name   Value separator name   Value
? name = codeproject & email = someone@gmail.com

This is how data are being passed to the receiving page when the method attribute of the <form> tag takes on the value of "get".

maxlength

You can add the maxlength attribute to an <input> element to restrict the maximum number of characters that a user is allowed to enter into that <input> element.

<input maxlength="10"> 

<label>

In Figure 2, each of the 2 text fields has been assigned a label using the <label> tag. The <label> tag defines a label for an <input> element. We can bind a <label> to an <input> element by assigning the id value of that <input> element to the for attribute of the <label> tag. When the user clicks on the text within the <label> element, it toggles the bound input element.

<label for="id value of the input element">Some Text</label>

<input type="password">

The <input type="password"> tag defines a password field. It is essentially a text field with the difference that the characters entered into it are masked in the form of asterisks or circles.

Add the highlighted code on the upper part of Figure 6 to index.html. This will create 2 password fields that look exactly like the two text fields above it. When you enter some texts into these password fields, you will notice that each character that you enter has been turned into either an asterisk or a circle as shown on the lower part of Figure 6.

Figure 6: Password Fields

<input type="radio">

The <input type="radio"> tag defines a radio button. Radio buttons usually come in groups of at least two that share the same value for their name attributes but different value for their value attributes. A user can only select one of them in a group at any one time.

Add the highlighted code on the upper part of Figure 7 to index.html. This will create 2 radio buttons for selection of gender as shown on the lower part of Figure 7. The 2 radio buttons share the same name as "gender" which identifies them as a group and only one gender can be chosen in this group. If you change one of the name to a different value, you will break this rule and both buttons can be chosen at the same time. Of course, it makes no sense for gender selection.

Figure 7: Radio Buttons

We can make one of the options as default by using checked attribute as follows:

<input type="radio" id="male" name="gender" value="male" checked> 

Next, we will use <fieldset> tag to create a border to group the 2 radio buttons and use <legend> tag to add a descriptive caption.

<fieldset> and <legend>

The <fieldset> tag is used to group related elements in a form by drawing a border around them. The <legend> tag is used to specify a caption for this border.

Let's modify the code on the highlighted area on the upper part of Figure 8 of index.html. This will draw a border around the 2 radio buttons for gender selection with a caption called "Gender" as shown on the lower part of Figure 8.

Figure 8: Border with Caption

<input type="checkbox">

The <input type="checkbox"> tag defines a checkbox for users to select or unselect an option. Like radio buttons, checkboxes usually come in groups. However, unlike radio buttons, a user can select more than one checkbox options.

Add the highlighted code on the upper part of Figure 9 to index.html. This will create 6 radio buttons for selection of hobbies as shown on the lower part of Figure 9. The 6 radio buttons share the same name as "hobbies" which identifies them as a group and zero or more options can be chosen in this group.

Figure 9: Checkboxes

<select> and <option>

The <select> and <option> tag are used together to create a drop-down list. Each item of the drop-down list is assigned to the value of an <option> tag and its textual description is enclosed between the <option> tag and its corresponding </option> tag. The collection of all the <option> and </option> pairs are then placed between a <select> tag and its corresponding </select> tag.

Add the highlighted code on the upper part of Figure 10 to index.html. This will create a drop-down list of zodiac signs as shown on the lower part of Figure 10.

Figure 10: Drop-down List

By default, users can only select one option in the <select> drop-down list. This can be modified to allow multiple selection by adding a multiple attribute to the <select> tag.

<select multiple>
    <option>Aries</option>
    <option>Taurus</option>
</select>

<textarea>

The <textarea> tag defines a multi-line text area the size of which can be specified using rows and cols attributes:

  • rows specifies the height of the text area in terms of number of lines. The default value is 2.
  • cols specifies the width of the text area in terms of average character width. The default value is 20.

Add the highlighted code on the upper part of Figure 11 to index.html. This will create a text area of 10 rows tall by 30 columns wide as shown on the lower part of Figure 11.

Figure 11: Text Area

Besides rows and cols attributes, we can also include disabled and readonly attributes in the <textarea> tag to control how users use the text area.

disabled

The disabled attribute specifies that an <input> element is unusable and un-clickable. Disabled <input> element will not be submitted.

<input disabled>

readonly

The readonly attribute specifies that an <input> element cannot be modified.

<input readonly>

<input type="file">

The <input type="file"> tag defines an upload button for users to select and upload a file.

Add the highlighted code on the upper part of Figure 12 to index.html. This will create an upload button where a user can click to select a file to upload as shown on the lower part of Figure 12.

Figure 12: File Upload

HTML5 Form

So far, we have constructed an HTML4 form. A major drawback of HTML4 form is the lack of built-in input controls and validation. For example, a web form may need to implement measures to control and validate such things like password field cannot be empty, email and date entered by a user are in their expected formats, age is entered as digits, and number entered is within certain range. These measures are often than now implemented using JavaScript code.

HTML5 has sought to minimize the dependency and need for separate scripting by introducing new HTML5 form elements as well as adding new attributes to the exsiting HTML4 form elements. In other words, HTML5 has brought new lease of life to rejuvenate the aging HTML4 form.

There is one caveat though - Not all browsers support all the new HTML5 elements and attributes as of now. Our HTML5 form will work fine in the latest Google Chrome browser but not others. However, if they are not supported, they will behave as regular text fields. In time to come, all browsers will support the new HTML5 form fully as it is the W3C's recommendations. So go ahead and start using it now.

HTML5 Input Type

HTML5 has introduced several new input types for forms with better input control and validation. We will incorporate 4 of them into index.html - email, date, color, and url.

<input type="email">

The <input type="email"> is used for input fields that should contain an email address and will automatically validate that the entry is of valid email format when the form is submitted. Change the email field in index.html (Figure 2) from "text" to "email", launch it on a (Chrome) browser, enter a non-email text, and press the submit button, you should see some alert message. (Figure 13)

<input type="email" id="email" name="email">
Figure 13: Email Field

<input type="date">

The <input type="date"> defines a date-picker. Add the following code to index.html after the "gender" radio buttons. This will pop-up a date-picker interface when a user clicks on it to select a date. (Figure 14)

<p class="particulars">
    <label for="dateofbirth">Date of Birth</label>
</p>
<input type="date" id="dateofbirth" name="dateofbirth">
Figure 14: Date-picker

<input type="color">

The <input type="color"> defines a color-picker. Add the following code to index.html after the "hobbies" checkboxes. This will pop-up a color-picker interface when a user clicks on it to select a color. (Figure 15)

<p class="particulars">
    <label for="favoritecolor">Favorite Color</label>
</p>
<input type="color" id="favoritecolor" name="favoritecolor">
Figure 15: Color-picker

<input type="url">

The <input type="url"> is used for input fields that should contain a URL address and will automatically validate that the entry is of valid url format when the form is submitted. Add the following code to index.html after the "aboutme" textarea. Launch it in a (Chrome) browser, enter a non-URL text, and press the submit button, you should see some alert message. (Figure 16)

<p class="particulars">
    <label for="weblink">Web Link</label>
</p>
<input type="url" id="weblink" name="weblink">
Figure 16: URL Field

Input Types Get Together

As you would have noticed by now, while the <input> element is the most important building block of HTML forms, the type attribute is the most important attribute of the <input> element. In a nut shell, the <input> element defines a data field that accept input from users while its type attribute controls the data type.

I have put together all the input types of HTML4 and HTML5 in Table 1 with descriptions and code snippets for easy reference and try out. The upper color zone of the table contains HTML4 input types while the lower color zone the HTML5 input types.

Table 1: HTML4 and HTML5 Input Types
type Description / Code Snippet
text

The <input type="text "> tag defines a one-line free text field with no line breaks

<form onsubmit="alert(document.getElementById('name').value);return false;">
Full Name: <input type="text" id="name" name="name" placeholder="First name, last name" required autofocus>
<input type="submit" value="Submit">
</form>
password

The <input type="password"> tag defines a one-line free text field for password that is masked with no line breaks

<form onsubmit="alert(document.getElementById('password').value);return false;">
Password: <input type="password" id="password" name="password" required pattern="[\w]{8,}" title="min 8 alphanumerics">
<input type="submit" value="Submit">
</form>
radio

The <input type="radio"> tag defines a radio button. Radio buttons usually come in groups of at least 2 that share the same value for their name attributes but different value for their value attributes

<input type="radio" id="male" name="gender"  value="male">Male
<input type="radio" id="female" name="gender" value="female">Female
checkbox

The <input type="checkbox"> tag defines a checkbox for users to select or unselect an option. A user can select more than one checkbox options in a group of related checkboxes

<input type="checkbox" id="hobbies" name="hobbies" value="Coding">Coding
file

The <input type="file"> defines a file upload control for users to select and upload a file

Portrait: <input type="file" id="portrait" name="portrait"> 
submit

The <input type="submit"> defines a submit button. When a user clicks the submit button, it sends the form data to a file specified in the action attribute of the <form> tag

<form onsubmit="alert('Welcome to CodeProject!');return false;">
<input type="submit" name="submit" id="submit" value="Sign up">
</form>
reset

The <input type="reset"> defines a reset button to clear all the entries and selections in a form

<input type="reset">
button

The <input type="button"> defines a button which can be used to initiate any event related to the button

<button type="button" onclick="alert('Hello CodeProject!')">Say Hello!</button>
image

The <input type="image"> defines a clickable image button which can be used to initiate any event related to the button.

<form onsubmit="alert('Welcome to CodeProject Workspaces!');return false;">
<input type="image" src ="workspaces32.png" name="img" alt="Workspace">
</form>
hidden

The <input type="hidden"> takes an arbitrary string that is not displayed to the users. Its name and value will still be passed to the receiving page upon submission.

<input type="hidden" name="secret" id="secret" value="I love CodeProject!">
<input type="button" value="I have a secret" onclick="alert(getElementById('secret').value)">
email

The <input type="email"> defines a text fields that should contain a email address and will automatically validate that the entry is of valid email format when the form is submitted

<form onsubmit="alert(document.getElementById('email').value);return false;">
Email: <input type="email" id="email" name="email" placeholder="someone@gmail.com" required>
<input type="submit" value="Submit">
</form>
date

The <input type="date"> defines a date-picker

<form onsubmit="alert(document.getElementById('dateofbirth').value);return false;">
Date of Birth: <input type="date" id="dateofbirth" name="dateofbirth">
<input type="submit" value="Submit">
</form>
color

The <input type="color"> defines a color-picker

<form onsubmit="alert(document.getElementById('favoritecolor').value);return false;"> Favorite Color: <input type="color" id="favoritecolor" name="favoritecolor"> <input type="submit" value="Submit"> </form>
<form onsubmit="alert(document.getElementById('favoritecolor').value);return false;">
Favorite Color: <input type="color" id="favoritecolor" name="favoritecolor">
<input type="submit" value="Submit">
</form>
url

The <input type="url"> is used for input fields that should contain a URL address and will automatically validate that the entry is of valid url format when the form is submitted

<form onsubmit="alert(document.getElementById('weblink').value);return false;">
My Home Page: <input type="url" id="weblink" name="weblink" placeholder="http://">
<input type="submit" value="Submit">
</form>
datetime

The <input type="datetime"> defines a control for setting the element's value to a string representing a date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601, with the time zone set to UTC

<form onsubmit="alert(document.getElementById('deadline').value);return false;">
Deadline: <input type="datetime-local" id="deadline" name="deadline">
<input type="submit" value="Submit">
</form>
datetime-local

The <input type="datetime-local"> defines a control for setting the element's value to a string representing a date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601, with no time zone

<form onsubmit="alert(document.getElementById('localdatetime').value);return false;">
Local Date Time: <input type="datetime-local" id="localdatetime" name="localdatetime">
<input type="submit" value="Submit">
</form>
month

The <input type="month"> defines a date consisting of a year and a month encoded according to ISO 8601, with no time zone

<form onsubmit="alert(document.getElementById('month').value);return false;">
Select a month: <input type="month" id="month" name="month">
<input type="submit" value="Submit">
</form>
week

The <input type="week"> defines a date consisting of a year and a week number encoded according to ISO 8601, with no time zone

<form onsubmit="alert(document.getElementById('week').value);return false;">
Select a week: <input type="week" id="week" name="week">
<input type="submit" value="Submit">
</form>
time

The <input type="time"> defines a time (hour, minute, seconds, fractional seconds) with no time zone encoded according to ISO 8601

<form onsubmit="alert(document.getElementById('time').value);return false;">
Select a time: <input type="time" id="time" name="time">
<input type="submit" value="Submit">
</form>
number

The <input type="number"> is used for input fields that should contain a numeric value and will automatically validate that the entry is of number when the form is submitted

<form onsubmit="alert(document.getElementById('capacity').value);return false;">
Capacity: <input type="number" id="capacity" name="capacity" min="1" max="9" step="2">
<input type="submit" value="Submit">
</form>
range

The <input type="range"> is used for input fields that should contain a value from a range of numbers

<form onsubmit="alert(document.getElementById('rate').value);return false;">
Rate: 1 <input type="range" id="rate" name="rate" min="1" max="5"> 5
<input type="submit" value="Submit">
</form>
search

The <input type="search"> is essentially similar to a text field but semantically set to contain search keywords

<form onsubmit="window.open('http://lmgtfy.com/?q='+document.getElementById('askgoogle').value);return false;">
Ask Google: <input type="search" id="askgoogle" name="askgoogle">
<input type="submit" value="Submit">
</form>
tel

The <input type="tel">is essentially similar to a text field but semantically set to contain telephone number

<form onsubmit="alert(document.getElementById('mobile').value);return false;">
Mobile: <input type="tel" id="mobile" name="mobile">
<input type="submit" value="Submit">
</form>

Seeing is believing, The best way to get to know these input types better (especially those that are not used in index.html) is to try them out, Start a text editor, create an empty HTML document as follows:

<!DOCTYPE html>
<html>
<body>
<!-- place your code below -->
           
            
<!-- end -->
</body>
</html>

Type the code snippets in between the 2 comment tags, save it with .html extension, and view the outcome on a (Chrome) browser. I hereby declare that they shall be your homework. Poke tongue | ;-P

HTML5 Form Elements

We will look at 3 new form elements introduced by HTML5 - <datalist>, <output>, and <keygen>.

<datalist>

The <datalist> element specifies a list of pre-defined options that are bound to an <input> element. It looks like the <select> element of Figure 10 but with the added auto-complete function. When a user types into the <input> text field, the matching options from the datalist will appear in a drop-down list.

Replace the <select> code in index.html (Figure 10) with the following code and launch it on a (Chrome) browser. As you enter some text, you will observe that a list of options matching your characters appear in the drop-down list. (Figure 17) The list attribute of the <input> element is assigned the id's value of the <datalist>, i.e. "zodiac", in this way they are bound together to provide the auto-complete feature.

<p class="particulars">
    <label for="zodiac">Zodiac</label>
</p>
<input list="zodiac" name="zodiac">
<datalist id="zodiac">
    <option value="Aries">
    <option value="Taurus">
    <option value="Gemini">
    <option value="Cancer">
    <option value="Leo">
    <option value="Virgo">
    <option value="Libra">
    <option value="Scorpio">
    <option value="Sagittarius">
    <option value="Capricorn">
    <option value="Aquarius">
    <option value="Pisces">
</datalist>
Figure 17: Auto Complete Drop-down List

<output>

The <output> element is used to display the result of a calculation on the browser, an operation that is usually performed by some JavaScript code. Open a new HTML page in your text editor, type and save the following code as output.html. Launch it on a (Chrome) browser, you should see the screen as shown in Figure 18.

You can change the numbers in either of the text boxes and their sum will be updated automatically. Notice that we have used <input type="number"> that provides a spinner with up-down arrows in Chrome browser.

<!DOCTYPE html>
<html>
<body>
<h1>Addition</h1>
<form oninput="result.value=parseInt(first.value) + parseInt(second.value)">
      <input type="number" id="first" value="50">
    + <input type="number" id="second" value="50">
    = <output name="result" for="first second">100</output>
</form>
</body>
</html>
Figure 18: Calculation without Script

<keygen>

The <keygen> element is used to generate a public key / private key pair. The private key is encrypted and stored in the local key store while the public key is submitted with the form data. It is intended for use with web-based certificate management systems which is beyond the scope and objective of this article. However, you can view a demo of <keygen> by tying out the following code and view its outcome on a browser as shown in Figure 19.

<!DOCTYPE html>
<html>
<head>
<title>keygen Demo</title>
</head>
<body>
<h1>keygen Demo</h1>
<form action="acknowledge.html" method="get">
  Passphrase: <input type="text" name="passphrase">
  Encryption: <keygen name="enckey" keytype="rsa">
  <input type="submit">
</form>
</body>
</html> 
Figure 19: keygen Demo

Enough is Enough?

By now, you may think you have learned enough already. You may think you can skip the rest of the article and jump right to the end to get the code for linking index.html to style.css, so that you can call it a day. Suddenly, your phone beeps. You client has just sent you a message with the following 4 new requirements to be implemented in index.html:

  • Always position the cusor on Name field on page load;
  • Make the Name, Email, and Password fields compulsory;
  • Provide hints on Name, Email, Password, and Web Link fields; and
  • Password field must consist of 8 or more alphanumeric characters.

This timely message has woken you up to the fact that you still have some distance to go. So press on...

HTML5 Form Attributes

In order to implement the 4 new requirements, you have to get familiar with the new form attributes introduced by HTML5. Let meet them one by one.

placeholder

When attached to an input field, the placeholder attribute shows a hint in the empty input field that describes the expected value or format, e.g. first name followed by a comma then last name, or an expected email format. The placeholder attribute works with input types of "text", "password", "email", "url", "search", and "tel".

<input placeholder="First name, last name">

required

When attached to an input field, the required attribute specifies that the input field must be filled out before the form can be submitted. An error message will displayed when an input field with required attribute is not filled up when the submit button is clicked. The required attribute works with input types of "text", "password", "email", "radio", "checkbox", "date", "file", "url", "search", "tel", and "number".

<input required>

autofocus

When attached to an input field, the autofocus attribute specifies that the input field should automatically get focused on page load.

<input autofocus>

pattern

When attached to an input field, the pattern attribute specifies the expected pattern (length, data type, format) of the input value and automatically performs validation when the submit button is clicked. (The pattern is expressed in Regular Expression which is beyond the scope of this article.) An error message will displayed when the input value to an input field does not match the regular expression of the pattern attribute of that input field when the submit button is clicked. In our example, the pattern attribute in the password field in index.html specifies that its input value (password) must consist of 8 or more alphanumeric characters.

<input pattern="[\w]{8,}">

autocomplete

The autocomplete attribute specifies whether a form or input field should have its autocomplete turned on or off. When autocomplete is on, the browser will auto-complete values based on values that a user has entered before. The autocomplete attribute works with <form> and the <input> types of "text", "password", "email", "url", date", "range", "color", "search", and "tel".

<form autocomplete="off">
<input type=text" name="fullname" autocomplete="on">

form

We have learned previously that all form elements must be placed explicitly inside the <form> and </form> tags. HTML5 has broken this restriction by introducing a new attribute that is literally called "form". This "form" attribute specifies the HTML form a form element belongs to through the id of that HTML form. In this way, the form element is no longer confined to between the <form> and</form> tags and can be placed anywhere in the HTML document.

<form action="acknowledge.html" id="form1">
    Last Name: <input type="text" name="firstname"><br>
    <input type="submit" value="Submit">
</form>
    First Name: <input type="text" name="lastname" form="form1"> 

novalidate

The novalidate is a form attribute. When attached to a form, it specifies that the input data of the form will not be validated on submission.

<form novalidate>

formaction

The formaction attribute is used with input types of "submit" and "image". It specifies the URL of a file that will receive and process the input data when the form is submitted. When present, the formaction attribute overrides the action attribute of the <form> element.

<input type="submit" formaction="process.aspx" value"Submit">

formenctype

The formenctype attribute is used with input types of "submit" and "image". It specifies how the form-data should be encoded for submission. When present, the formaction attribute overrides the enctype attribute of the <form> element.

<input type="submit" formenctype="multipart/form-data" value="Submit">

formmethod

The formmethod attribute is used with input types of "submit" and "image". It specifies the HTTP method for sending form data to the URL of a file when the form is submitted. When present, the formmethod attribute overrides the method attribute of the <form> element.

<input type="submit" formaction="process.aspx" formmethod="post" value"Submit">

formnovalidate

The formnovalidate attribute is used with input type of "submit". It specifies that the form data will not be vaildated for submission. When present, the formnovalidate attribute overrides the novalidate attribute of the <form> element.

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

formtarget

The formtarget attribute is used with input types of "submit" and "image". It indicates where to display the response that is received after submitting the form. When present, the formtarget attribute overrides the target attribute of the <form> element.

<input type="submit" formtarget="_blank" value="Submit">

height and width

The height and width attributes are only used with the input type of "image". They specify the height and width of the <input type="image"> element.

<input type="image" src="workspaces32.png" height="32" width="330">

list

The list attribute refers to a <datalist> element that contains pre-defined options for the <input> element where the list attribute attached. It was used in the example in Figure 17.

min and max

The min and max attributes specify the minimum and maximum value for an <input> element. It was used in the examples of "number" type and "range" type in Table 1.

<input type="image" src="workspaces32.png" width="330" height="32">

multiple

The multiple attribute is used with <input> types of "file" and "email". It specifies that the user can enter more than one value in the <input> element that it attached.

Upload photos: <input type="file" name="photos" multiple>

step

The step attribute specifies the legal number intervals for an <input> element. It works with the <input> type of "date", "datetime", "datetime-local", "month", "time", "week", "number", and "range". It was used in the example of "number" type in Table 1.

Meeting the New Requirements

Having learned the new HTML5 form attributes, you can now add "autofocus", "placeholder", "required", and "pattern" to the respective <input> elements in index.html as follows:

<input type="text" id="name" name="name" placeholder="First name, last name" required autofocus>

<input type="email" id="email" name="email" placeholder="someone@gmail.com" required>

<input type="password" id="password" name="password" required pattern="[\w]{8,}">

<input type="password" id="confirmpassword" name="confirmpassword" required>

<input type="url" id="weblink" name="weblink" placeholder="http://">

This new code should meet the 4 new requirements set by your client.

Crossing the Finishing Line...

We are about to cross the finishing line. Wait, have we forgotten something? Oops, we have not applied make-up to index.html. Let's add the following line of code to the <head> section of index.html so that it can tap on the CSS rules declared inside the style.css file. You should then be able to see the completed index.html appears like Figure 1 on a (Chrome) browser. Check out its behavior by testing the various input controls and validations, and submitting the form.

<head>
<title>Formidable Forms with HTML5</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>

We have reached the end of the journey. Take a breather and I shall return, until then... Sleepy | :zzz:

HTML5 becomes W3C RECOMMENDATION!

After a decade of development, the W3C has promoted HTML5 to "Recommendation" on 28 October 2014 -HTML5 IS A W3C RECOMMENDATION. W3C's "Recommendation" status represents the highest level of maturation, officially making the HTML5 a formal standard. Cheer!

Reference

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Peter Leow
Instructor / Trainer
Singapore Singapore
子曰:"三人行,必有我师焉;择其善者而从之,其不善者而改之
 
"There is always something we can learn from another person. Choose to follow his strengths while use his shortcomings to reflect upon ourselves."
― Confucius
 
“Live as if you were to die tomorrow. Learn as if you were to live forever.”
― Mahatma Gandhi
Follow on   LinkedIn

Comments and Discussions

 
GeneralSir you are gentleman and a scholar PinmemberFidelFig30-Jan-15 16:21 
GeneralRe: Sir you are gentleman and a scholar PinmvpPeter Leow30-Jan-15 20:20 
GeneralMy vote of 5 Pinmemberarroway27-Jan-15 23:08 
GeneralRe: My vote of 5 PinmvpPeter Leow30-Jan-15 20:19 
QuestionExcellent Article PinprofessionalAneesh Divakaran27-Jan-15 21:53 
AnswerRe: Excellent Article PinmvpPeter Leow30-Jan-15 20:19 
QuestionEstá muy interesante. PinmemberMember 1133102427-Jan-15 20:29 
AnswerRe: Está muy interesante. PinmvpPeter Leow27-Jan-15 21:08 
QuestionMy vote of 5 PinmemberAlex JMW27-Jan-15 19:00 
AnswerRe: My vote of 5 PinmvpPeter Leow27-Jan-15 21:09 
GeneralMy vote of 5 PinmemberAndyKEnZ27-Jan-15 1:09 
GeneralRe: My vote of 5 PinmvpPeter Leow27-Jan-15 21:09 
GeneralMy vote of 5 PinprofessionalPrasad Khandekar26-Jan-15 8:36 
GeneralRe: My vote of 5 PinmvpPeter Leow26-Jan-15 15:28 
QuestionMy vote of 5 PinmemberTokinabo17-Nov-14 11:43 
AnswerRe: My vote of 5 PinprofessionalPeter Leow17-Nov-14 15:07 
QuestionAgain, a very nice article! PinprofessionalJames Jensen28-Apr-14 5:08 
GeneralRe: Again, a very nice article! PinprofessionalPeter Leow28-Apr-14 5:19 
GeneralMy vote of 5 Pinmemberloh cindy19-Apr-14 16:46 
GeneralRe: My vote of 5 PinprofessionalPeter Leow28-Apr-14 5:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150301.1 | Last Updated 26 Jan 2015
Article Copyright 2014 by Peter Leow
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid