Formidable Forms with HTML

PeterLeow
22.8K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

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. In a way, web forms have become the de facto ways of interaction between websites and their users. With the proliferation of social media, web forms have also become the ubiquitous ways of communication between users of social networking websites.

In a nutshell, a web form usually consists of one or more form widgets such as text fields, text areas, drop-down lists, checkboxes, radio buttons, reset button, or submit buttons. Like their counterparts in paper forms, these form widgets are usually labeled with words to describe their purpose. Through such form widgets, users can enter, select, and submit data to the server for processing.

There are two parts to completing the learning of web forms — the client side and the server side. The client side focuses on building your first web form using HTML, while the server side focuses on writing server-side scripts to process the data submitted via your first web form.

In this tutorial, you will embark on a hands-on learning journey to creating a modern web form on the client side.

Looking Ahead...

At the end of the learning journey you will have created a web form as animated in Figure 1 using HTML.

alt text Figure 1: My First Web Form

Setting the Stage

Create a folder called, say, webform On your computer. In it, create an HTML file called, say, index.html with the following code:

<!DOCTYPE html>
<html>
<head>
<title>Hands-on with Web Forms</title>
</head>
<body>
<div class="container">
  <header>
    <h1>Hands-on with Web Forms</h1>
  </header>
  <div class="form">
    <!-- Add your code here -->
  </div>
</div>
</body>
</html>
Setting the Stage

In the area marked by <!-- Add your code here --> comment inside index.html, you will add the HTML code to build your first web form.

As you move along, you will notice the inclusion of class attributes inside the opening tags of some of the HTML elements, e.g. <div class="container"> and <div class="form"> in index.html. If you are not familiar with CSS, it is suffice to note that these class attributes are being used as selectors to select the styles for their corresponding HTML elements. The styles are being saved in an external CSS file. At the end of this learning journey, you will learn to import it into index.html to produce the look and feel that you have seen in Figure 1.

To make your hands-on more realistic, you will need another file to receive and process the form data submitted by index.html. In the folder that contains index.html, create another HTML file called, say acknowledge.html, with the following code:

<!DOCTYPE html>
<html>
<head>
<title>Acknowledgement</title>
</head>
<body>
<h1>Acknowledgement</h1>
<h3>Form data in <em>name=value</em> pairs delimited by <em>&amp;</em> sign:</h3>
<div style="overflow-wrap: break-word">
  <script>
    document.write(decodeURIComponent(window.location.search).substring(1));
  </script>
<div> 
</body>
</html>

acknowledge.html will simply echoes whatever form data it has received.

Let the journey begin...

Building Your First Web Form

Start by adding the following HTML code to index.html:

<form id="userform" action="acknowledge.html" method="get">

  <p class="caption">
    <label for="username">Name</label>
  </p>
  <p>
    <input type="text" id="username" name="username">
  </p>

  <p>
    <input type="submit" class="bottom" id="usersubmit" name="usersubmit" value="Sign up">
  </p>
  
</form>

Launch the index.html on a browser or run the code in the Form, Text Field, and Submit Button code section below:

Form, Text Field, and Submit Button

You should see an animated output as shown in Figure 2:

alt text Figure 2: Form, Text Field, and Submit Button

You have tasted the fruit, it's time to learn about the code in index.html.

<form>...</form>

All web forms start with an opening <form> tag and a corresponding closing </form> tag inside which resides form widgets like text fields. In index.html, the <form> tag has been given three attributes as described in Table 1:

Table 1: <form>Attributes
Form AttributeDescription
idContains a value that can be used to reference an HTML element in JavaScript and CSS. In our example, userform is the id of the form.
actionContains the URL of a file to which the form data will be sent on submission. In our example, acknowledge.html is the file that will receive the form data.
methodDefines how the form data is sent. The value get given in our example will cause the form data to be sent via the HTTP GET method by which the form data are appended as name=value pairs to the URL of the receiving page on submission. Another value for the method attribute is post which will cause the form data to be sent via the HTTP POST method by which the form data are embedded in the body of the request message instead of being exposed as part of the URL on the browser's address bar.

<input type="text">

<input type="text"> defines a single-line text field that accepts any arbitrary string. In index.html, we have added one text field for the user to enter a name. It has two attributes, i.e. id and name, both are given the same value called username. (Of course, you can give them other values or different values if you like.) You have already learned the purpose of id. As for the name attribute, its value, i.e. username, together with the data that the user entered will be sent over to the receiving file, e.g acknowledge.html in our example, as a name=value pair on form submission. For example, if the user enters a value, say Peter Leow, into this text field and clicks the Sign up button, this value will be sent to the server as a query string in the form of username=Peter+Leow and picked up by the receiving server-side script that looks for username in the query string.

Value

The value attribute contains the value of the text entered into the text field. A text field can be given a default value via the value attribute. For example, the following code snippet will render a text field with a default value Peter Leow in it:

<input type="text" id="username" name="username" value="Peter Leow">

Note the following observations from Figure 2:

The space between Peter and Leow has been converted to a + sign as a result of URL encoding:

The text field is accompanied by a caption, Name, assigned via the <label> tag.

<label>

It is customary to label an input field, since paper form times, with a descriptive caption that reflects its purpose. This is the job of the HTML <label> tab. Each <label> tag has a for attribute that takes the id value of the element to which it is bound. For example, in index.html,

<label for="username">Name</label>

is bound to:

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

In this way, whenever the user clicks on the caption of a <label> element, the element bound to this label is given the focus.

<input type="submit">

<input type="submit"> defines a submit button. When a user clicks the submit button, it sends the form data to a file specified by the value of the action attribute of the <form> tag. Unlike other form elements, the submit button does not need a separate <label> tag. Its caption is assigned via its own value attribute. For example, in index.html, the submit button has a caption that reads "Sign up" which is assigned via the value attribute as shown:

<input type="submit" class="bottom" id="usersubmit" name="usersubmit" value="Sign up">

Note the following observations from Figure 2:

On form submission, the submit button itself is also being submitted to acknowledge.html in the form of a name=value pair, i.e. usersubmit=Sign+up, delimited from username=Peter+Leow by a & sign in the query string in our example. That explains the query string username=Peter+Leow&usersubmit=Sign+up that you have seen in Figure 2.

As the form is submitted via get method, this query string is appended to the URL and is visible in the address bar of the browser as shown in Figure 2.

Continue to add different form widgets inside the <form>...</form>...

<input type="password">

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

Add the following code to index.html between the Name text field and the Sign up button.

<p class="caption">
  <label for="userpassword">Password</label>
</p>
<p>
  <input type="password" id="userpassword" name="userpassword">
</p>

Launch the index.html on a browser or run the code in the Password Field code section below:

Password Field

You should see an animated output as shown in Figure 3:

alt text Figure 3: Password Field

The password field looks exactly like the text field above it. The similarity, however, ends once you start entering text into it: each character that you enter is marked with an asterisk or a circle.

On submission, the password entry is added as userpassword=123456 to the query string.

Note:

In real applications, never transmit confidential data across the web using form get method as they are visible to the prying eyes in the browser's address bar, use post method together with HTTP Secure (HTTPS) protocol, i.e. https:// instead of "http://. For learning purpose, get method is used so that you can visualize the raw query string.

<input type="radio">

<input type="radio"> defines a radio button. Radio buttons usually come in a group of at least two that share the same value for their name attributes (so as to identify them as a group) but different values for their value attributes (indicating different options). A user can select only one option from a group.

Add the following code to index.html between the Password text field and the Sign up button.

<fieldset>
  <legend>Gender</legend>

  <label for="male">Male</label> 
  <input type="radio" id="male" name="gender" value="male">

  <label for="female">Female</label>
  <input type="radio" id="female" name="gender" value="female">

</fieldset>

Launch the index.html on a browser or run the code in the Radio Buttons code section below:

Radio Buttons

You should see an animated output as shown in Figure 4:

alt text Figure 4: Radio Buttons

The two radio buttons have different values for their value attributes, i.e. value="male" and value="female", to represent different gender options, while sharing the same value for the name attributes, i.e. name="gender", which identifies them as a group and only one gender option can be selected in this group. If you assign the name attributes with different values, you will break this rule and both radio buttons can be selected at the same time. Of course, it makes no sense for gender selection.

On submission, the selected gender option is added as gender=male to the query string.

checked

You can make one of the options in a radio button group as a default selection by adding a checked attribute to the radio button of the default value. For example, you can make the female option as a default selection like this:

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

In Figure 4, notice that the radio buttons are being surrounded by a border with a caption that reads Gender. They are the creation of <fieldset> and <legend>.

<fieldset>

The <fieldset> tag is used to group HTML elements visibly by drawing a border around them.

<legend>

Used with <fieldset>, <legend> tag specifies a caption for the border created by <fieldset>.

<input type="select"> and <option>

<input type="select"> and <option> tags are used together to create a drop-down list. Each item of the drop-down list is assigned to the value attribute of an <option> tag and its textual description is placed between the opening <option> tag and the closing </option> tag. The collection of all the <option> and </option> pairs are then placed between the opening <select> tag and the closing </select> tag.

Add the following code to index.html between the Gender radio button group and the Sign up button.

<p class="caption">
  <label for="resstatus">Residential Status</label>
</p>
<p>  
  <select id="resstatus" name="resstatus">      
	<option value="Citizen">Citizen</option>
	<option value="PR">Permanent Resident</option>
	<option value="Foreigner">Foreigner</option>
  </select> 
</p>

Launch the index.html on a browser or run the code in the Drop-down List code section below:

Drop-down List

The code above will add a drop-down list of residential statuses as animated in Figure 5:

alt text Figure 5: Drop-down List

On form submission, the selected residential status is added as resstatus=Citizen to the query string.

selected

You can pre-select an option by adding a selected attribute to the <option> tag that you want to pre-select. The following code snippet pre-selects the PR option:

<option value="PR" selected>Permanent Resident</option>

multiple

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 as shown in the following code snippet:

<select id="resstatus" name="resstatus" multiple>

<input type="textarea">

<input type="textarea"> defines a multi-line text area the size of which can be specified using rows and cols attributes as follows:

rows

rows attribute specifies the height of the text area in terms of number of lines, e.g. rows="10". The default value is 2.

cols

cols attribute specifies the width of the text area in terms of average character width, e.g. cols="30". The default value is 20.

Add the following code to index.html between the Residential Status drop-down list and the Sign up button.

<p class="caption">
  <label for="aboutme">About Me</label>
</p>
<p>
  <textarea id="aboutme" name="aboutme" rows="10" cols="30"></textarea>
</p> 

Launch the index.html on a browser or run the code in the Text Area code section below:

Text Area

The code above will add a text area of 10 rows tall by 30 columns wide as animated in Figure 6:

alt text Figure 6: Text Area

On form submission, the multi-line text are added to the query string.

Besides the rows and cols attributes, there are also disabled and readonly attributes you can add to the <textarea> tag or other form elements to control how users use form elements.

disabled

The disabled attribute specifies that a form element is unusable and un-clickable. Disabled form element will not be submitted. For example, the following code snippet will render an unselectable drop-down list:

<select id="resstatus" name="resstatus" disabled>

readonly

The readonly attribute specifies that the content of a form element cannot be modified. For example, the following code snippet will render a read-only text area:

<textarea id="aboutme" name="aboutme" rows="10" cols="30" readonly>write something about yourself</textarea>

<input type="email">

<input type="email"> defines an email field that expects an email address and will automatically validates that the entry is of valid email format on form submission.

Add the following code to index.html between the About Me text area and the Sign up button.

<p class="caption">
  <label for="useremail">Email</label>
</p>
<p>
  <input type="email" id="useremail" name="useremail">
</p>

Launch the index.html on a browser or run the code in the Email Field code section below:

Email Field

The code above will add an email field as animated in Figure 7:

alt text Figure 7: Email Field

As observed, if you enter a non-email text into the email field, and hit the Sign up button, the form will not be submitted. Instead, a message box shows up prompting you to enter an email address.

<input type="url">

<input type="url"> defines a URL field that expects a URL address and will automatically validates that the entry is of valid URL format on form submission.

Add the following code to index.html between the Email field and the Sign up button.

<p class="caption">
  <label for="weblink">Web Link</label>
</p>
<p>
  <input type="url" id="weblink" name="weblink">
</p>

Launch the index.html on a browser or run the code in the URL Field code section below:

URL Field

The code above will add a URL field as animated in Figure 8:

alt text Figure 8: URL Field

As observed, if you enter a non-URL text into the email text field, and hit the Sign up button, the form will not be submitted. Instead, a message box shows up prompting you to enter a URL address.

<input type="date">

<input type="date"> defines a date field that expects a date and will automatically validates that the entry is a valid date on form submission.

Add the following code to index.html between the URL field the Sign up button.

<p class="caption">
  <label for="dateofbirth">Date of Birth</label>
</p>
<p>
  <input type="date" id="dateofbirth" name="dateofbirth">
</p>

Launch the index.html on a browser or run the code in the Date Field code section below:

Date Field

Upon click, the date field opens an interactive calendar where a user can select a date as animated in Figure 9:

alt text Figure 9: Date Field

As observed, if you enter an invalid date directly into the date field without invoking the date picker, and hit the Sign up button, the form will not be submitted. Instead, a message box shows up prompting you to enter a date.

On form submission, the selected date is sent as part of the query string on form submission, e.g. dateofbirth=2017-02-28.

<input type="color">

<input type="color"> defines a colour field.

Add the following code to index.html between the Date of Birth field the Sign up button.

<p class="caption">
  <label for="favoritecolor">Favorite Color</label>
</p>
<p>
  <input type="color" id="favoritecolor" name="favoritecolor">
</p>

Launch the index.html on a browser or run the code in the Colour Field code section below:

Colour Field

Upon click, the colour field opens an interactive colour picker where a user can select a colour as animated in Figure 10:

alt text Figure 10: Colour Field

On form submission, the colour code of the selected colour is sent, e.g. #ff0000 for red colour.

<input type="checkbox">

<input type="checkbox"> defines a checkbox. Like radio buttons, checkboxes usually come in a group of at least two that share the same value for their name attributes (so as to identify them as a group) but different values for their value attributes (indicating different options). Unlike radio buttons, however, a user can select multiple checkbox options from a group.

Add the following code to index.html between the Favorite Color field and the Sign up button.

<p class="caption">
  <label for="hobbies">Hobbies</label>
</p>
<p>
  <input type="checkbox" class="hobbies" name="hobbies[]" value="coding">Coding<br>
  <input type="checkbox" class="hobbies" name="hobbies[]" value="reading">Reading<br>
  <input type="checkbox" class="hobbies" name="hobbies[]" value="swimming">Swimming<br> 
  <input type="checkbox" class="hobbies" name="hobbies[]" value="jogging">Jogging<br>
  <input type="checkbox" class="hobbies" name="hobbies[]" value="eating">Eating<br>
  <input type="checkbox" class="hobbies" name="hobbies[]" value="others">Others<br>
</p>

Launch the index.html on a browser or run the code in the Checkboxes code section below:

Checkboxes

The code above will add six checkboxes as animated in Figure 11:

alt text Figure 11: Checkboxes

The six checkboxes have different values for their value attributes, i.e. value="coding", value="reading", etc., to represent different hobbies, while sharing the same value for the name attributes, i.e. name="hobbies[]", which identifies them as a group.

Note:

Since multiple selection is allowed and expected in checkbox group, their names are suffixed with [] so that they can be read as an array by the server-side script.

On form submission, the selected hobby options are added as hobbies[]=reading&hobbies[]=jogging to the query string.

Like radio buttons, you can make some of the options in a checkbox group as default selections by adding a checked attribute to the appropriate checkboxes. For example, you can make the Coding and Reading options as default selections like this:

<input type="checkbox" class="hobbies" name="hobbies[]" value="coding" checked>Coding<br>
<input type="checkbox" class="hobbies" name="hobbies[]" value="reading" checked>Reading<br>

<input type="list"> and <datalist>

<input type="list"> defines an auto-complete field the value of which is drawn from the list of options values defined under <datalist>. It works like a <select> drop-down list but with the added auto-complete feature — when a user types into the text field, the matching option values from the <datalist> will appear in a drop-down list.

Add the following code to index.html between the Hobbies checkbox group and the Sign up button.

<p class="caption">
  <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>

Launch the index.html on a browser or run the code in the Auto-complete Drop-down List code section below:

Auto-complete Drop-down List

The code above will add an auto-complete drop-down list of Zodiacs as animated in Figure 12:

alt text Figure 12: Auto-complete Drop-down List

Enter L into the Zodiac text field, you should see a drop-down list containing the matching values, i.e. Leo and Libra, appears.

On form submission, the selected zodiac name is added to the query string, e.g. zodiac=Leo.

<input type="file">

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

Add the following code to index.html between the Zodiac Field and the Sign up button.

<p class="caption">
  <label for="portrait">Portrait</label>
</p>
<p>
  <input type="file" id="portrait" name="portrait">
</p>

Launch the index.html on a browser or run the code in the File code section below:

File

The code above will add an upload button where a user can browse for a file to upload as animated in Figure 13:

alt text Figure 13: File

In our example, only the file name is sent to acknowledge.html as portrait=koala.jpg in the query string, not the file content. To be able to upload the content of a file to the server, you code must implement these features:

  • The <form> must use method="post"; and

  • The <form> must include this attribute enctype="multipart/form-data". It declares that the type of content is binary and will not be encoded.

Putting them together, a web form for file upload should look something like this:

<form id="userform" action="process.php" method="post" enctype="multipart/form-data">
  <input type="file" id="portrait" name="portrait">
  <!-- other form widgets -->
</form>

On the server side, a script, e.g. process.php, is needed to handle the uploaded file content. Since this tutorial focuses on client side, it will stop short of delving into that.

<input type="reset">

<input type="reset"> defines a reset button. When a user clicks the reset button, it resets all the form widgets to their default values. Like the submit button, the reset button does not need a separate <label> tag. Its caption is assigned via its own value attribute.

Add the following code to index.html just above the Sign up submit button.

<input type="reset" class="bottom" value="Reset">

Launch the index.html on a browser or run the code in the Reset Button code section below:

Reset Button

The code above will add a reset button where a user can click to reset all the form widgets to their default values as animated in Figure 14:

alt text Figure 14: Reset Button

Input Types Get Together

As you would have noticed by now, while the <input> tag is the most important building block of HTML forms, the type attribute is the most important attribute of the <input> tag. In a nutshell, while the <input> tag defines a data field that accept input from users, it is its type attribute that controls the type of data that is to be accepted.

I have put together all the input types, some of which you have already met before, in Table 2 with descriptions and code snippets for easy reference and trying out.

Doing is believing, The best way to get to know these input types (especially those you have met before) is to try them out, Open a text editor, create an HTML document called, say test.html, with the following code:

<!DOCTYPE html>
<html>
<body>
  <!-- add code snippet below -->

</body>
</html>

As you walk through the various input types in Table 2, add the corresponding code snippet below the comment tag inside test.html , and observe the outcome by launching test.html in a browser. I hereby declare that this shall be your homework. 

Table 2: Summary of Input Types
TypeDescription / Code Snippet
textThe <input type="text "> tag defines a one-line free text field with no line breaks.
<form onsubmit="alert(document.getElementById('name').value);return false;">
  Name: <input type="text" id="name" name="name">
  <input type="submit" value="Submit">
</form>
passwordThe <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">
  <input type="submit" value="Submit">
</form>
radioThe <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 have 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
checkboxThe <input type="checkbox"> tag defines a checkbox for users to select or un-select 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
fileThe <input type="file"> defines a file upload widget for users to select and upload a file.
Portrait: <input type="file" id="portrait" name="portrait">
submitThe <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
tag.
<form onsubmit="alert('Welcome to PeterLeowBlog.com!');return false;">
  <input type="submit" name="submit" id="submit" value="Sign up">
</form>
resetThe <input type="reset"> defines a reset button to reset all the entries and selections in a form to their default value.
<input type="reset" value="Reset">
buttonThe <input type="button"> defines a clickable button which can be used to trigger an event when the button is clicked.
<input type="button" value="Click Me" onclick="alert('Welcome to PeterLeowBlog.com!')">
You can also create a clickable button using the HTML <button> tag like this:
<button type="button" onclick="alert('Welcome to PeterLeowBlog.com!')">Click Me</button>
imageThe <input type="image"> defines a clickable image button which can be used to trigger an event when the image is clicked.
<form onsubmit="alert('Welcome to PeterLeowBlog.com!');return false;">
 <input type="image" src="https://en.gravatar.com/userimage/89030985/4e416e4d0b5f28768d4ad747299a099b.jpeg" name="img" alt="Workspace">
</form>
hiddenThe <input type="hidden"> is used to hold data but not displaying them in the browser. This is usually done intentionally using code. Though hidden, such data are sent together with the rest of form data on form submission.
<input type="hidden" name="secret" id="secret" value="I love PeterLeow's Code Blog!">
<input type="button" value="I have a secret" onclick="alert(getElementById('secret').value)">
emailThe <input type="email"> defines a text field that expects an email address and will automatically validate that the entry is of valid email format on form submission.
<form onsubmit="alert(document.getElementById('email').value);return false;">
  Email: <input type="email" id="email" name="email">
  <input type="submit" value="Submit">
</form>
dateThe <input type="date"> defines a date field.
<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>
colorThe <input type="date"> defines a colour field.
<form onsubmit="alert(document.getElementById('favoritecolor').value);return false;">
  Favorite Color: <input type="color" id="favoritecolor" name="favoritecolor">
  <input type="submit" value="Submit">
</form>
urlThe <input type="url"> defines a text field that expects a URL address and will automatically validate that the entry is of valid url format on form submission.
<form onsubmit="alert(document.getElementById('weblink').value);return false;">
  My Home Page: <input type="url" id="weblink" name="weblink">
  <input type="submit" value="Submit">
</form>
numberThe <input type="number"> defines an input field that expects a numeric value and will automatically validate that the entry is a number on form submission. Most browsers render it as a spinner with up/down buttons.
<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>
rangeThe <input type="range"> defines an input field that expects a value from a range of numbers. Most browsers render it as a slider with a handle for sliding between two 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>
searchThe <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>
telThe 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>

Enough is Enough?

By now, you may think you have learned enough already. You may think you can skip the rest of the tutorial and call it a day. Suddenly, your phone beeps. You client has just sent you a message with the following four new requirements to be implemented in index.html:

  • Always position the cursor 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 eight 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...

Form Attributes

In order to implement the four new requirements, you have to get familiar with more form attributes other than those you have met previously, Let's meet them one by one.

placeholder

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

<input type="text" placeholder="First name Last name">

required

When included in an <input> tag, 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 type="text" required>

autofocus

When included in an <input> tag, the autofocus attribute specifies that the input field should automatically get focused on page load.

<input type="text" autofocus>

pattern

When included in an <input> tag, 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 tutorial.) 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 eight or more alphanumeric characters.

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

autocomplete

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

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

Note:

For the autocomplete feature to work, you may have to turn on such a feature in your browser via the settings. Autocomplete is sometimes called autofill.

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"> widget.

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

min and max

The min and max attributes specify the minimum and maximum value for an input field. It was used in the examples of number type and range type in Table 2.

<input type="range" id="rate" name="rate" min="1" max="5">

step

The step attribute specifies the legal number intervals for an <input> widget. It works with input types of datenumber, and range. It was used in the example of number type in Table 2.

<input type="number" id="capacity" name="capacity" min="1" max="9" step="2">

multiple

The multiple attribute is used with <input type="file">, <input type="mail">, and <select> widgets. When present, it specifies that multiple files can be selected, multiple emails can be entered, and multiple options can be selected in the respective widgets.

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

form

We have learned previously that all form widgets must be placed explicitly inside the <form> and </form> tags. Modern HTML, however, has broken this restriction by introducing a new attribute that is literally called form. This form attribute specifies the HTML form a form widget 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 onsubmit="alert(document.getElementById('firstname').value + document.getElementById('lastname').value);return false;">
  First Name: <input type="text" id="firstname"><br>
  <input type="submit" value="Submit">
</form>
Last Name: <input type="text" id="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 form 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> tag.

<input type="submit" formaction="process.php" 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> tag.

<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> tag.

<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> tag.

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

Meeting the New Requirements

Having learned the many 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="username" name="username" placeholder="First name Last name" required autofocus>
<input type="email" id="useremail" name="useremail" placeholder="someone@gmail.com" required>
<input type="password" id="userpassword" name="userpassword" required pattern="[\w]{8,}">
<input type="url" id="weblink" name="weblink" placeholder="http://">

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

Crossing the Finishing Line...

We are about to cross the finishing line. Wait, something is amiss! Your form does not look and feel like that one being animated in Figure 1. Oops, you have not applied any CSS styles to index.html.

Download and save the style.css file into the same folder as that of index.html, then 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.

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

Launch your index.html on a browser and you should be able to see that it appears like that one being animated in Figure 1.

Congratulation! You have successfully created your first web form using modern HTML.

The article Formidable Forms with HTML appeared first on Peter Leow's Code Blog.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content