0% found this document useful (0 votes)
20 views19 pages

04 HTML Forms

Uploaded by

zoom1
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
20 views19 pages

04 HTML Forms

Uploaded by

zoom1
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 19

HTML Forms

HTML Forms are required when you want to collect some data from the site visitor. For example
during user registration you would like to collect information such as name, email address, credit
card, etc.

A form will take input from the site visitor and then will post it to a back-end application such as
CGI, ASP Script or PHP script etc. The back-end application will perform required processing on
the passed data based on defined business logic inside the application.

There are various form elements available like text fields, text area fields, drop-down menus, radio
buttons, checkboxes, etc.

The HTML <form> tag is used to create an HTML form and it has following syntax:

<form action="Script URL" method="GET|POST">

form elements like input, textarea etc.

</form>

Form Attributes
Apart from common attributes, following is a list of the most frequently used form attributes:

Attribut Description
e

action Backend script ready to process your passed data.

method Method to be used to upload data. The most frequently used are GET and POST
methods.

target Specify the target window or frame where the result of the script will be displayed.
It takes values like _blank, _self, _parent etc.

enctype You can use the enctype attribute to specify how the browser encodes the data
before it sends it to the server. Possible values are:

 application/x-www-form-urlencoded - This is the standard method most


forms use in simple scenarios.
 mutlipart/form-data - This is used when you want to upload binary data in
the form of files like image, word file etc.

Note: You can refer to Perl & CGI for a detail on how form data upload works.
HTML Form Controls
There are different types of form controls that you can use to collect data using HTML form:

 Text Input Controls


 Checkboxes Controls
 Radio Box Controls
 Select Box Controls
 File Select boxes
 Hidden Controls
 Clickable Buttons
 Submit and Reset Button
Text Input Controls
There are three types of text input used on forms:

 Single-line text input controls - This control is used for items that require only one line of
user input, such as search boxes or names. They are created using HTML <input> tag.
 Password input controls - This is also a single-line text input but it masks the character as
soon as a user enters it. They are also created using HTML <input> tag.
 Multi-line text input controls - This is used when the user is required to give details that
may be longer than a single sentence. Multi-line input controls are created using
HTML <textarea> tag.

Single-line text input controls


This control is used for items that require only one line of user input, such as search boxes or
names. They are created using HTML <input> tag.

Example
Here is a basic example of a single-line text input used to take first name and last name:

<!DOCTYPE html>

<html>

<head>

<title>Text Input Control</title>

</head>

<body>

<form >

First name: <input type="text" name="first_name" />

<br>

Last name: <input type="text" name="last_name" />

</form>

</body>

</html>

This will produce following result:


First name:
Last name:

Attributes
Following is the list of attributes for <input> tag for creating text field.

Attribute Description

Type Indicates the type of input control and for text input control it will be set totext.

Name Used to give a name to the control which is sent to the server to be recognized
and get the value.

Value This can be used to provide an initial value inside the control.

Size Allows to specify the width of the text-input control in terms of characters.

maxlengt Allows to specify the maximum number of characters a user can enter into the
h text box.

Password input controls


This is also a single-line text input but it masks the character as soon as a user enters it. They are
also created using HTML <input> tag but type attribute is set to password.

Example
Here is a basic example of a single-line password input used to take user password:

<!DOCTYPE html>

<html>

<head>

<title>Password Input Control</title>

</head>

<body>

<form >

User ID : <input type="text" name="user_id" />

<br>

Password: <input type="password" name="password" />


</form>

</body>

</html>

This will produce following result:

User ID :
Password:

Attributes
Following is the list of attributes for <input> tag for creating password field.

Attribute Description

type Indicates the type of input control and for password input control it will be set
to password.

name Used to give a name to the control which is sent to the server to be recognized
and get the value.

value This can be used to provide an initial value inside the control.

size Allows to specify the width of the text-input control in terms of characters.

maxlengt Allows to specify the maximum number of characters a user can enter into the
h text box.

Multiple-Line Text Input Controls


This is used when the user is required to give details that may be longer than a single sentence.
Multi-line input controls are created using HTML <textarea> tag.

Example
Here is a basic example of a multi-line text input used to take item description:

<!DOCTYPE html>

<html>

<head>

<title>Multiple-Line Input Control</title>


</head>

<body>

<form>

Description : <br />

<textarea rows="5" cols="50" name="description">

Enter description here...

</textarea>

</form>

</body>

</html>

This will produce following result:

Description :

Attributes
Following is the list of attributes for <textarea> tag.

Attribut Description
e

name Used to give a name to the control which is sent to the server to be recognized
and get the value.

rows Indicates the number of rows of text area box.

cols Indicates the number of columns of text area box

Checkbox Control
Checkboxes are used when more than one option is required to be selected. They are also created
using HTML <input> tag but type attribute is set to checkbox.

Example
Here is an example HTML code for a form with two checkboxes:
<!DOCTYPE html>

<html>

<head>

<title>Checkbox Control</title>

</head>

<body>

<form>

<input type="checkbox" name="maths" value="on"> Maths

<input type="checkbox" name="physics" value="on"> Physics

</form>

</body>

</html>

This will produce following result:

Maths Physics

Attributes
Following is the list of attributes for <checkbox> tag.

Attribut Description
e

Type Indicates the type of input control and for checkbox input control it will be set
to checkbox.

Name Used to give a name to the control which is sent to the server to be recognized
and get the value.

Value The value that will be used if the checkbox is selected.

Checked Set to checked if you want to select it by default.

Radio Button Control


Radio buttons are used when out of many options, just one option is required to be selected. They
are also created using HTML <input> tag but type attribute is set to radio.

Example
Here is example HTML code for a form with two radio buttons:
<!DOCTYPE html>

<html>

<head>

<title>Radio Box Control</title>

</head>

<body>

<form>

<input type="radio" name="subject" value="maths"> Maths

<input type="radio" name="subject" value="physics"> Physics

</form>

</body>

</html>

This will produce following result:

Maths Physics

Attributes
Following is the list of attributes for radio button.

Attribut Description
e

Type Indicates the type of input control and for checkbox input control it will be set
to radio.

Name Used to give a name to the control which is sent to the server to be recognized
and get the value.

Value The value that will be used if the radio box is selected.

Checked Set to checked if you want to select it by default.

Select Box Control


A select box, also called drop down box which provides option to list down various options in the
form of drop down list, from where a user can select one or more options.

Example
Here is example HTML code for a form with one drop down box
<!DOCTYPE html>

<html>

<head>

<title>Select Box Control</title>

</head>

<body>

<form>

<select name="dropdown">

<option value="Maths" selected>Maths</option>

<option value="Physics">Physics</option>

</select>

</form>

</body>

</html>

This will produce following result:

Physics

Attributes
Following is the list of important attributes of <select> tag:

Attribut Description
e

Name Used to give a name to the control which is sent to the server to be recognized
and get the value.

Size This can be used to present a scrolling list box.

Multiple If set to "multiple" then allows a user to select multiple items from the menu.

Following is the list of important attributes of <option> tag:

Attribut Description
e

Value The value that will be used if an option in the select box box is selected.
selected Specifies that this option should be the initially selected value when the page
loads.

Label An alternative way of labeling options

File Upload Box


If you want to allow a user to upload a file to your web site, you will need to use a file upload box,
also known as a file select box. This is also created using the <input> element but type attribute is
set to file.

Example
Here is example HTML code for a form with one file upload box:

<!DOCTYPE html>

<html>

<head>

<title>File Upload Box</title>

</head>

<body>

<form>

<input type="file" name="fileupload" accept="image/*" />

</form>

</body>

</html>

This will produce following result:

Attributes
Following is the list of important attributes of file upload box:

Attribut Description
e

Name Used to give a name to the control which is sent to the server to be recognized
and get the value.

Accept Specifies the types of files that the server accepts.


Button Controls
There are various ways in HTML to create clickable buttons. You can also create a clickable button
using <input> tag by setting its type attribute to button. The type attribute can take the following
values:

Type Description

Submit This creates a button that automatically submits a form.

Reset This creates a button that automatically resets form controls to their initial values.

Button This creates a button that is used to trigger a client-side script when the user clicks
that button.

Image This creates a clickable button but we can use an image as background of the
button.

Example
Here is example HTML code for a form with three types of buttons:

<!DOCTYPE html>

<html>

<head>

<title>File Upload Box</title>

</head>

<body>

<form>

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

<input type="reset" name="reset" value="Reset" />

<input type="button" name="ok" value="OK" />

<input type="image" name="imagebutton" src="/html/images/logo.png" />

</form>

</body>

</html>
This will produce following result:n

Submit Reset

Hidden Form Controls


Hidden form controls are used to hide data inside the page which later on can be pushed to the
server. This control hides inside the code and does not appear on the actual page. For example,
following hidden form is being used to keep current page number. When a user will click next page
then the value of hidden control will be sent to the web server and there it will decide which page
has be displayed next based on the passed current page.

Example
Here is example HTML code to show the usage of hidden control:

<!DOCTYPE html>

<html>

<head>

<title>File Upload Box</title>

</head>

<body>

<form>

<p>This is page 10</p>

<input type="hidden" name="pagename" value="10" />

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

<input type="reset" name="reset" value="Reset" />


</form>

</body>

</html>

This will produce following result:

This is page 10

Submit Reset

The Action Attribute

The action attribute defines the action to be performed when the form is submitted.

The common way to submit a form to a server, is by using a submit button.


Normally, the form is submitted to a web page on a web server.

If the action attribute is omitted, the form will be redirected to the page it was submitted
from.

In the example above, a server-side script is specified to handle the submitted form:

<form action="demo_form_action.asp">

The Method Attribute

The method attribute specifies the HTTP method (GET or POST) to be used when
submitting the forms:

<form action="demo_form_action.asp" method="GET">

or:

<form action="demo_form_action.asp" method="POST">

When to Use GET?

You can use GET (the default method):

If the form submission is passive (like a search engine query), and without sensitive
information.

When you use GET, the form data will be visible in the page address:

demo_form_action.asp?firstname=Mickey&lastname=Mouse

When to Use POST?

If the form is updating data, or includes sensitive information (password).

POST offers better security because the submitted data is not visible in the page address.

Grouping Form Data with <fieldset>

The <fieldset> element groups related data in a form.

The <legend> element defines a caption for the <fieldset> element.

Example

<form action="demo_form_action.asp">
<fieldset>
<legend>Personal information:</legend>
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit"></fieldset>
</form>

This is how the HTML code above looks like in a browser:

Personal information:First name:


Mickey

Last name:
Mouse

Submit

Example

<form action="demo_form_action.asp">
<fieldset>
<legend>Personal information:</legend>
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit"></fieldset>
</form>

HTML: Validating a checkbox with HTML5:


While HTML5 form validation is typically about missing or invalid text inputs, there are
other form element types that also require attention. One of them being the humble
checkbox.

1. Checkbox validation using JavaScript


Suppose you have a form on your website that at the bottom asks people to "accept the
Terms and Conditions" or something similar. Basically you don't want the form to be
submitted unless this is checked.
Using vanilla JavaScript we can prevent form submission as follows:
<script type="text/javascript">

function checkForm(form)

...

if(!form.terms.checked) {

alert("Please indicate that you accept the Terms and Conditions");

form.terms.focus();

return false;

}
return true;

</script>

<form ... onsubmit="return checkForm(this);">

...

<p><input type="checkbox" name="terms"> I accept the <u>Terms and


Conditions</u></p>

<p><input type="submit"></p>

</form>
Example 1
Submit
I accept the Terms and Conditions

All this does is confirm before submitting the form that the checkbox is checked. If not,
an alert is displayed and focus is moved to the checkbox. Not the prettiest solution, but
functional in all browsers with JavaScript enabled.

2. HTML5 required input


Adding HTML5 validation to the checkbox is actually very simple. All you need to do is
include arequired attribute:
<form ... onsubmit="return checkForm(this);">

...

<p><input type="checkbox" required name="terms"> I accept the <u>Terms and


Conditions</u></p>

<p><input type="submit"></p>

</form>

This tells the browser that the form should not be allowed to submit without the
checkbox checked. Some, but not all, browsers will recognise and enforce this:

Submit
Example 2 I accept the Terms and Conditions

The advantage of the HTML5 form validation is that it happens before our JavaScript is
called, displays instructions and points the user to the relevant element.
Here you can see screen captures from Firefox and Chrome:
Text alert messages are generated entirely by the browser and will even translate
automatically into different languages - something that would be almost impossible
using just JavaScript.

The advantage for the user is that it's obvious which element is causing the problem
and there's no alert window that needs to be clicked away.

At time of writing Safari does not enforce required input fields. If you're using
Safari or another unsupporting browsers all the examples will just display the
JavaScript alert box.

3. Customised HTML5 messages

As you would hope it is possible to customize the messages that are displayed by the
browser with your own text, but this can only be done via JavaScript. You need to check
the validity state of the element yourself and set (and clear) the message explicitly:
<form ... onsubmit="return checkForm(this);">

...

<p><input onchange="this.setCustomValidity(validity.valueMissing ? 'Please


indicate that you accept the Terms and Conditions' : '');" id="field_terms"

type="checkbox" required name="terms"> I accept the <u>Terms and

Conditions</u></p>

<p><input type="submit"></p>

</form>

<script type="text/javascript">

document.getElementById("field_terms").setCustomValidity("Please indicate
that you accept the Terms and Conditions");

</script>
The block of JavaScript below the form is assigning our custom error message to the
checkbox when the page loads. We know that the checkbox is unchecked by default so
we need to tell the browser what message to display.
The onchange event handler on the checkbox then toggles the error message. When the
checkbox is valid (checked) the message is set to blank which tells the browser that it's
ok for the form to be submitted.
When the checkbox is not checked and the Submit button is clicked an alert is displayed
similar to the examples above, but using our text instead of the default.
Submit
Example 3 I accept the Terms and Conditions
Here you can see the custom message being displayed in Firefox:

Custom messages can be set in a similar manner for text and other elements, but you
will need to check the validity object states (validity.valueMissing,
validity.patternMismatch, ...) to determing the right message. See the link under
References for details.

4. Separating form from function


The previous example was starting to become a bit cluttered with two JavaScript script
blocks as well as the onsubmit and onchange event handlers inlined in the HTML.
We can separate the JavaScript code from the HTML and have the required event
handlers assigned after the page has loaded using an onload event listener.
Here first is the HTML with all JavaScript removed:
<form id="example4" ...>

...

<p><input id="field_terms" type="checkbox" required name="terms"> I accept the


<u>Terms and Conditions</u></p>

<p><input type="submit"></p>

</form>

And the JavaScript to reinstate the event handlers:


<script type="text/javascript">

document.addEventListener("DOMContentLoaded", function() {

var myForm = document.getElementById("example4");

var checkForm = function(e) {

...

if(!this.terms.checked) {
alert("Please indicate that you accept the Terms and Conditions");

this.terms.focus();

e.preventDefault(); // equivalent to return false

return;

};

// attach the form submit handler

myForm.addEventListener("submit", checkForm, true);

var myCheckbox = document.getElementById("field_terms");

var myCheckboxMsg = "Please indicate that you accept the Terms and
Conditions";

// set the starting error message

myCheckbox.setCustomValidity(myCheckboxMsg);

// attach checkbox handler to toggle error message

myCheckbox.addEventListener("change", function() {

this.setCustomValidity(this.validity.valueMissing ? myCheckboxMsg : "");

}, false);

}, false);

</script>

The forms behaviour should be unchanged:


Submit
Example 4 I accept the Terms and Conditions

While it looks much more complicated, this is a better solution because it allows for the
HTML and JavaScript to be maintained separately. The only hooks between them are
the id values for the form itself and the checkbox input element. Also gone are any
globally defined functions or variables.
The JavaScript can now be moved to a separate file, or converted to a code library
allowing for it to be reused with other forms.
The required attribute on checkboxes is supported in Internet Explorer 10 and
most/all other browsers exept for Safari which ignores the requirement.

5. CSS3 required styles


As we've see in other articles the valid/invalid state of a form element can be used to
provide visual feedback to the user - displaying a green thumbs up or checkmark for
example when the input requirements have been satisfied, or displaying a red outline or
warning symbol when they have not.
This is also possible with checkbox elements, just a bit trickier because you can't really
place anything on the inside.
Here's some sample code to get you started:
<style type="text/css">

input[type="checkbox"]:required:invalid + label { color: red; }

input[type="checkbox"]:required:valid + label { color: green; }

</style>

<form ...>

...

<p><input id="field_terms" type="checkbox" required name="terms">

<label for="field_terms">I accept the <u>Terms and Conditions</u></label></p>

...

</form>

The CSS depends of course on how you mark up form fields. In this case we've included
a labelelement alongside the checkbox which allows us to reference it using the CSS3
adjacent sibling selector. These styles are all being applied to the label element.
I accept the Terms and Conditions
Clicking on the checkbox or the label text will now toggle the checkbox state, and the
text will change from red to green. Basically, when the checkbox is happy, the label is
happy.
There are also clever ways of styling the label to look like a checkbox and hiding the
actual checkbox so you can use your own graphic, font icon or CSS creation:
<style type="text/css">

input[type="checkbox"]:required {

display: none;

input[type="checkbox"]:required:invalid + label:before {

content: "\2610";

padding-right: 0.2em;

font-size: 1.6em;

color: red;

input[type="checkbox"]:required:valid + label:before {

content: "\2611";

padding-right: 0.2em;

font-size: 1.6em;
color: green;

</style>

In this case we've used some UNICODE 'ballot box' characters for the on/off state. They
are prepended to the label, but actually toggling the checkbox in the background. We
know the checkbox is changing because that's what drives the CSS effect:
I accept the Terms and Conditions
The HTML for this example is the same as above.

You might also like