HTML forms tutorial: Difference between revisions

The educational technology and digital learning wiki
Jump to navigation Jump to search
 
(4 intermediate revisions by the same user not shown)
Line 1: Line 1:
{{Incomplete}}
{{Incomplete}}
{{web technology tutorial|Introductory}}
{{web technology tutorial|Introductory}}
<pageby nominor="false" comments="false"/>
<!-- <pageby nominor="false" comments="false"/> -->


== Introduction ==
== Introduction ==
Line 21: Line 21:
; Level and target population
; Level and target population
* Beginners
* Beginners
; Last major update
* 2009
; Remarks
; Remarks
* For the moment, this article is intended to be a "handout" for "lab" teaching. In other words, a teacher + hands-on activities are needed. In addition, we don't explain how to use a specific editing tool.
* This article was intended to be a "handout" for "lab" teaching. In other words, a teacher + hands-on activities are needed. In addition, we don't explain how to use a specific editing tool. Finally, contents should be adapted to HTML5.
* To do: develop each section and split into 4 different tutorials: forms, forms with JS, forms with PHP, and web applications and CGI principles
* To do: develop each section and split into 4 different tutorials: forms, forms with JS, forms with PHP, and web applications and CGI principles
</div>
</div>
Line 177: Line 179:
=== Select element ===
=== Select element ===


The select element either displays as a dropt down menu or a menu window from which the user can select one or more alternatives.
The select element either displays as a drop down menu or a menu window from which the user can select one or more alternatives.


  Countries I visited:
  Countries I visited:
<source lang="HTML5">
  <select name="country" size=1>
  <select name="country" size=1>
  <option>CH:  Switzeland</option>
  <option>CH:  Switzeland</option>
Line 186: Line 189:
  <option>A:  Austria</option>
  <option>A:  Austria</option>
  <option>I:  Italy</option>
  <option>I:  Italy</option>
</select>
</select>
</source>


====Select attributes====
====Select attributes====


'''Autofocus''': Gives focus to the drop-down list when the page is loaded <br/><br/>
'''Autofocus''': Gives focus to the drop-down list when the page is loaded
<select autofocus>
<source lang="HTML5">  
<select autofocus>
   <option value="2011">2011</option>
   <option value="2011">2011</option>
   <option value="2012">2012</option>
   <option value="2012">2012</option>
   <option value="2013">2013</option>
   <option value="2013">2013</option>
   <option value="2014">2014</option>
   <option value="2014">2014</option>
</select>
</select>
 
</source>


'''Note''': The autofocus attribute of the <select> tag is not supported in Internet Explorer 9 and earlier versions, or in Firefox.<br/><br/>
'''Note''': The autofocus attribute of the <select> tag is not supported in Internet Explorer 9 and earlier versions, or in Firefox.<br/><br/>


'''Disabled''': Specifies that the drop-down list is being disabled<br /><br />
'''Disabled''': Specifies that the drop-down list is being disabled
<select disabled>
<source lang="HTML5">  
<select disabled>
   <option value="2011">2011</option>
   <option value="2011">2011</option>
   <option value="2012">2012</option>
   <option value="2012">2012</option>
   <option value="2013">2013</option>
   <option value="2013">2013</option>
   <option value="2014">2014</option>
   <option value="2014">2014</option>
</select>
</select>
<br/><br />
</source>
'''Form''': Specifies the forms in which the selected field belongs to <br /> <br />
'''Form''': Specifies the forms in which the selected field belongs to
<form action="demo_form.asp" id="yearform">
<source lang="HTML5">  
<form action="demo_form.asp" id="yearform">
   Firstname:<input type="text" name="fname">
   Firstname:<input type="text" name="fname">
   <input type="submit">
   <input type="submit">
</form>
</form>


<select name="carlist" form="yearform">
<select name="carlist" form="yearform">
   <option value="2011">2011</option>
   <option value="2011">2011</option>
   <option value="2012">2012</option>
   <option value="2012">2012</option>
   <option value="2013">2013</option>
   <option value="2013">2013</option>
   <option value="2014">2014</option>
   <option value="2014">2014</option>
</select>
</select>
</source>
'''Note''': The form attribute is not supported in Internet Explorer.


'''Note''': The form attribute is not supported in Internet Explorer.<br/><br />
'''Multiple''': multiple options can be selected at once
 
<source lang="HTML5">  
'''Multiple''': multiple options can be selected at once <br /><br />
<select multiple>
<select multiple>
   <option value="2011">2011</option>
   <option value="2011">2011</option>
   <option value="2012">2012</option>
   <option value="2012">2012</option>
   <option value="2013">2013</option>
   <option value="2013">2013</option>
   <option value="2014">2014</option>
   <option value="2014">2014</option>
</select>
</select>
<br/><br />
</source>  
 
'''Name''': Name of drop-down list  
'''Name''': Name of drop-down list  
<select name="years">
<source lang="HTML5">
<select name="years">
   <option value="2011">2011</option>
   <option value="2011">2011</option>
   <option value="2012">2012</option>
   <option value="2012">2012</option>
   <option value="2013">2013</option>
   <option value="2013">2013</option>
   <option value="2014">2014</option>
   <option value="2014">2014</option>
</select>
</select>
<br/><br />
</source>
'''Size''': the number of visible options in a drop-down list  
'''Size''': the number of visible options in a drop-down list  
<select size="3">
<source lang="HTML5">
<select size="3">
   <option value="2011">2011</option>
   <option value="2011">2011</option>
   <option value="2012">2012</option>
   <option value="2012">2012</option>
   <option value="2013">2013</option>
   <option value="2013">2013</option>
   <option value="2014">2014</option>
   <option value="2014">2014</option>
</select>
</select>
<br/><br />
</source>  
'''Note''': In Chrome and Safari, this attribute may not work as expected for size="2" and size="3".<br /><br />
'''Note''': In Chrome and Safari, this attribute may not work as expected for size="2" and size="3".<br /><br />



Latest revision as of 14:49, 22 April 2018

Introduction

Learning goals
  • Learn function an purpose of HTML forms
  • Learn how to code some kinds of forms
  • Understand how JavaScript may be used to process forms
  • Understand how forms can be processed with PHP
Prerequisites
Concurrent
Moving on
Level and target population
  • Beginners
Last major update
  • 2009
Remarks
  • This article was intended to be a "handout" for "lab" teaching. In other words, a teacher + hands-on activities are needed. In addition, we don't explain how to use a specific editing tool. Finally, contents should be adapted to HTML5.
  • To do: develop each section and split into 4 different tutorials: forms, forms with JS, forms with PHP, and web applications and CGI principles

HTML Forms are the "basic" HTML elements for client or server-side interactivity. DHTML (i.e. the combination of HTML, DOM, JavaScript and CSS add extra possibilities.

Let's discuss a short example:

<?xml version = "1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
  <head>
    <title>HTML form</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  </head>

  <body>

    <h1>HTML form elements</h1>

<form method="get" action="#">

<h2>Personal data</h2>

<p>
<strong>Name</strong><br/>
<input type="text" name="name" size="25" />
</p>

<p>
<strong>Firstname</strong><br/>
<input type="text" name="firstname" size="25"/>
</p>

<p>
<strong>I'd like to have some documentation</strong>
<input type="checkbox" name="doc_wanted"/>
</p>

<p>
<strong>Countries I visited</strong>
<select name="country" size=1>
	  <option>CH:  Switzerland</option>
	  <option>D:   Germany</option>
	  <option>F:   France</option>
	  <option>A:   Austria</option>
	  <option>I:   Italy</option>
	</select>
</p>
<p>
<strong>Gender</strong>
<input type="radio" name="gender" value="1"/>Male
<input type="radio" name="gender" value="2"/>Female
</p>

<p>
<strong>Preferred main color</strong>
<input type="radio" name="colorprefs" value="y"/>Yellow
<input type="radio" name="colorprefs" value="b"/>Blue
<input type="radio" name="colorprefs" value="r"/>Red
<input type="radio" name="colorprefs" value="g"/>Green
</p>

<h2>Majoring in</h2>
Vous may choose more than one:
<p>
<input type="checkbox" name="domain1" />Education
<input type="checkbox" name="domain2" />Psychologie
<input type="checkbox" name="domain3" />Computer Science
<input type="checkbox" name="domain4" />International Relations
<input type="checkbox" name="domain5" />Business Administration
<input type="checkbox" name="domain6" />Other
</p>

<h2>Comments</h2>

Tell me anything you want to ... <p>
<textarea name="comments" rows=4 cols=60></textarea>
</p>

<h2>More</h2>
<p>
Input button for JS coding: <input type="button" value="Press me"/>
</p>
<p>
Password field: <input type="password" name="pw"/>
</p>

<p>
<input type="reset" value="Reset the form"/>
<input type="submit" value="Submit"/>
</p>
</form>
<hr/>
</body>
</html>

Live code: 1-demo-html-form-els.html

HTML form example

This example demoes the most important HTML forms elements. HTML forms all must be children of the <form>....</form> element and which usually is used in the following way:

 <form name="myform" action="#" method="get">
      
 </form>
  • The action attribute defines what resource will deal with it. "#" means "this page" and is used for JavaScript code
  • the method attribute defines which of the HTTP methods is being used, usually "GET" or "POST" (see below).
  • the name attribute is optional, but recommended for DOM processing with JavaScript.

Inside forms, a designer must enter two kinds of elements:

  • various user input widgets (as shown below)
  • Text that will display information like prompts that the user needs in order to understand what kind of input he/she should enter

Of course, one also can use all sorts of structuring elements (e.g. paragraphs, table elements or line breaks)

Input elements

Input elements come in several forms (HTML5 includes additional ones). In this introductory tutorial, we will not introduce the hairy details (there are some), but just provide a few typical examples.

Each button usually should have a name attribute. This will make it much easier to process the code. In addition, the name tag may have extra functionality, e.g. it will group radio buttons together.

Text: a simple text box that allows input of a single line of text.

Enter something: <input type="text" name="name" size="25" />

checkbox: A check box that can be either on or off.

Yes I agree: <input type="checkbox" name="want_doc"/>

radio: Radio buttons allow a user to make a choice between one or more alternatives. Preferred main color:

<input type="radio" name="colorprefs" value="y"/>Yellow
<input type="radio" name="colorprefs" value="b"/>Blue
<input type="radio" name="colorprefs" value="r"/>Red
<input type="radio" name="colorprefs" value="g"/>Green

file: allow the user to select a file for upload

<input name="uploadfile" type="file">

reset: A reset button allows the user to the the browser to restore the values to their initial values.

<input type="reset" value="Reset the form"/>

submit: This button that tells the browser to submit the form (typically to send it to a server)

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

button: This is a button that is used for JavaScript programming.

 <input type="button" value="Press me"/>

password: Allow users to enter a password. Caracters are shown as asterisks or circles.

 <input type="password" name="pwd">

Select element

The select element either displays as a drop down menu or a menu window from which the user can select one or more alternatives.

Countries I visited:
 <select name="country" size=1>
	  <option>CH:  Switzeland</option>
	  <option>D:   Germany</option>
	  <option>F:   France</option>
	  <option>A:   Austria</option>
	  <option>I:   Italy</option>
 </select>

Select attributes

Autofocus: Gives focus to the drop-down list when the page is loaded

 
 <select autofocus>
  <option value="2011">2011</option>
  <option value="2012">2012</option>
  <option value="2013">2013</option>
  <option value="2014">2014</option>
 </select>

Note: The autofocus attribute of the <select> tag is not supported in Internet Explorer 9 and earlier versions, or in Firefox.

Disabled: Specifies that the drop-down list is being disabled

 
 <select disabled>
  <option value="2011">2011</option>
  <option value="2012">2012</option>
  <option value="2013">2013</option>
  <option value="2014">2014</option>
 </select>

Form: Specifies the forms in which the selected field belongs to

 
 <form action="demo_form.asp" id="yearform">
  Firstname:<input type="text" name="fname">
  <input type="submit">
 </form>

 <select name="carlist" form="yearform">
  <option value="2011">2011</option>
  <option value="2012">2012</option>
  <option value="2013">2013</option>
  <option value="2014">2014</option>
 </select>

Note: The form attribute is not supported in Internet Explorer.

Multiple: multiple options can be selected at once

 
 <select multiple>
  <option value="2011">2011</option>
  <option value="2012">2012</option>
  <option value="2013">2013</option>
  <option value="2014">2014</option>
 </select>

Name: Name of drop-down list

 
 <select name="years">
  <option value="2011">2011</option>
  <option value="2012">2012</option>
  <option value="2013">2013</option>
  <option value="2014">2014</option>
 </select>

Size: the number of visible options in a drop-down list

 
 <select size="3">
  <option value="2011">2011</option>
  <option value="2012">2012</option>
  <option value="2013">2013</option>
  <option value="2014">2014</option>
 </select>

Note: In Chrome and Safari, this attribute may not work as expected for size="2" and size="3".

see more: http://www.w3schools.com/tags/tag_select.asp

Text area element

The text area allows users to enter larger text. This element is also used for programming through the web editors.

Example:

Tell me anything you want to ... 
<textarea name="comments" rows=4 cols=60></textarea>

Server-side forms processing

HTML forms can be processed by a webserver in two ways, either trough the older, easier and still more popular HTTP requests or through the JavaScript XMLHttpRequest object (AJAX)

The principle for both is the same. The client (i.e. your web browser) sends some data to a URL. The webserver will hand over your data to the resource (program) identified by the URL, e.g. a PHP script.

HTTP

The Hypertext Transfer Protocol (HTTP) is a communications protocol used to transfer or convey information on the World Wide Web. (Wikipedia).

In the most simple case, a HTTP round trip from browser to server and back can be explained with the following picture:

A simple HTTP request and answer

Messages sent from browser to server and the other way round have two parts

  1. Information that the user will not see
  2. Data

Browser requests consist of the following:

A Request line, such as GET /images/logo.gif HTTP/1.1, which requests the file logo.gif from the /images directory
Headers that will give the server information about your browser, cookies etc.
An empty line
An optional message body (e.g. POST contents from a form)

Here is a sample message sent from the browser to the server and that request that the server sends the contents of the resource identified as http://www.example.com/index.

 GET /index.html HTTP/1.1
 Host: www.example.com

Server replies include:

A first line that includes a status code (e.g. "200 OK" means "here is what you asked")
Some other information about the context, the server and the most importantly the content type.
A blank line
The data

Here is a sample message sent from the server to the browser in response:

HTTP/1.1 200 OK
Date: Sun, 06 May 2007 19:13:32 GMT
Server: Apache/2.2.3 (Win32) PHP/5.1.5
X-Powered-By: PHP/5.1.6
Content-Length: 252
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: text/html
 .... Contents, e.g. HTML code ....

Request methods, server-side scripts and database

HTTP defines eight request methods that a browser may send to a web server. When dealing with forms, developers usually use either the "GET" or the "POST" request.

Forms submission with HTTP
The difference between "GET" and "POST"

GET will request a resource from the server. I.e. this is the method used when you retrieve a normal web page.

  • However, GET requests also may be used to transfer data to a resource (i.e. a script) that will deal with it.
  • In the latter case, the data are transferred in the URL which allows users to bookmark a request. Get should be used with care, since web crawlers or hackers can exploit this. Below is an example of a GET request that sends data.
http://wiki.somewhere.intheworld/mediawiki/index.php?title=Main_Page&action=history

POST is used to send data to a resource.

  • POST will include the form data to be processed in the body of the request, e.g. you can not see it in your browser.
  • POST also allows to send large information (unless GET which is limited)

Modern web servers now usually include a direct method that allows the server to provide the resource with data that comes from the user. The common gateway interface (CGI) which is still used for certain applications, defined how webservers can talk to external programs.

URL encoding

Data that is sent from the browser to the web server is specially encoded and must be decoded by the server. This has historical reasons, i.e. the Internet only could deal with a limited character set.

According to Wikipedia, the list of reserved characters that must be specially encoded is show in the following table:

Reserved characters after percent-encoding
! * " ' ( ) ; : @ & = + $ , / ? % # [ ]
%21 %2A %22 %27 %28 %29 %3B %3A %40 %26 %3D %2B %24 %2C %2F %3F %25 %23 %5B %5D

In addition, all non-ASCII characters (e.g. accents) are also encoded. This is why you sometimes see really ugly URLs.

Use of databases

A request processing script often will "talk" to a database as the following picture shows:

Forms submission with HTTP and databases

Web development

In order to promote modularity and reuse of code, modern web development is usually based on a three tiers model that we show below.

Three tier web application architecture

In larger web development shops, one usually separates as best three types of work:

  • People that deal with style (CSS)
  • People that deal with contents (usually through a CMS
  • People that deal with client coding (either HTML, HTML forms plus JavaScript or portalware configuration plus templating)
  • People that deal with server-side coding
  • People that deal with database issues

An other trend is represented by the so-called AJAX technique which is a combination of:

XHTML (or HTML) and CSS, for marking up and styling information.
The DOM accessed with a client-side scripting language, usually ECMAScript (JavaScript)
The XMLHttpRequest object is used to exchange data asynchronously with the web server.
XML is sometimes used as the format for transferring data between the server and client.

The principle is the same, but instead of sending a new page to the navigator, it will send data that then is incorporated with "DOM surgery" in the page from which the request originated.

Processing forms with PHP

PHP scripts are put on a web server (like HTML files). However, the server deals with PHP in a very different way:

  • When the user requests and HTML file, it is just delivered to the browser as is.
  • If the user requests a PHP file, then the procedure is different. PHP files are executed first by the web server and only the result (which usually is a page including some HTML code) is then sent to back the browsers. In other words, there is now way to have a look at the source code of a PHP file, if you don't have server access.

PHP code can be be small, e.g. sit in a single file. Or it may consists of hundreds of files. Many (or most) popular portalware is coded with PHP, including this wiki.

PHP code is inserted between: <?php ..... ?>. Make sure not remove any of these "XML processing instruction" tags.

<?php echo("I am a php instruction\n"); ?>

Comments are inserted after //.

Example

The HTML form (contents of a file that you might call quiz.html). Copy/Paste the contents below into an HTML authoring tool or a text editor.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <title>Simple test with</title>
</head>

<body>
 <h1>Simple test with PHP</h1>

Please fill in the following questionnaire:

<hr>

 <form action="quiz-processing.php" method="post">

 Please enter your name: 
 <input type="text" name="username">

 <br/>
 What do you know about HTML ?
 <input type="radio" name="choice" value="1" checked>little
 <input type="radio" name="choice" value="2">some
 <input type="radio" name="choice" value="3">everything

 <br/>
 What is your programming experience ?
 <input type="radio" name="choice2" value="1" checked>none
 <input type="radio" name="choice2" value="2">some
 <input type="radio" name="choice2" value="3">good
 <P>
 <input type="submit" value="See result!">
 </form>

</body>
</html>

Contents of the Php file that you should call quiz-processing.php (else change its name in the action attribute of the HTML file). Copy/paste the contents below into a text editor or an HTML authoring tool that can handle PHP.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  <html>
    <head><title>Simple test with</title></head>
    <body>
      <h1>Simple test with PHP</h1>
    <p>
    Test results are not really interesting, since the the questions themselves were uninteresting. 
    It's up to to come up with something that is better in all respects.
    </p>
 <hr>

  <?php
  // Max error reporting. Errors are reported in the log file (apache2/logs/error.log)
  // To see errors displayed in the HTML page, change the ''php.ini file'': display_errors = On

  error_reporting (E_ALL);

  // Get variables from the form
  $choice  = $_POST['choice'];
  $choice2 = $_POST['choice2'];
  $user    = $_POST['username'];

  // Compute the score
  $score = $choice + $choice2;

  // Display the score
  echo "Hi $user. Thanx for filling in the form.";
  echo "<h3>Your score is " . $score . "</h3>";

  if ($score < 3) {
    echo "<p>You are a beginner</p>";
  } elseif ($score < 5) {
    echo "<p>You have some knowledge</p>";
  } else {
    echo "<p>You are an expert !</p>";
  }

  //  phpinfo(); // remove the commenting if you want to see what PHP sees.
  ?>

  <hr/>
  <a href="quiz.html">Go back to the quiz</a>

  <hr>DKS - 2007
  </body>
</html>

Playing at home

To play with a webserver on your personal computer, install a WAMP package for Windows or a LAMP package for Unix, or a MAMP package for the Mac.

LAMP/WAMP means
Linux or Windows, the operating system;
Apache, the Web server;
MySQL, the database management system
PHP

Forms processing with JavaScript

Forms processing with JavaScript in your browser is somewhat easier, since you don't need to have access to the webserver) and somewhat more difficult (since JavaScript/DOM programming is a bit more difficult than PHP programming).

Let's examine an simple HTML example that displays two series of radio buttons. Each series is identified by a name attribute. Series one by "question1" and series two by "question2". We will present two coding solutions: Old style and new style.

Old style JavaScript

Old style JavaScript is a bit easier to understand, but does have the disadvantage that HTML and JavaScript code is not cleanly separated. E.g. you could not use the same HTML page for processing with PHP without remove the onsubmit="give_feedback()" fragment from the code below.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
  <head>
    <title>XHTML form example</title>
    <meta http-equiv="Content-Type" content="text/html;charset=iso8859-1" />
    <script type="text/javascript" language="Javascript" src="2-xhtml-radio-buttons.js">
    </script>
  </head>
  
  <body>
    <h1>XHTML form example</h1>

    <p>Below is a simple quiz, please fill it in.</p>

    <form name="quiz" action="#" method="get" onsubmit="give_feedback()">  <br/>
        <p>
        Among those three choices, what do you prefer to do to relax ? <br/>
	Watching TV <input type="radio" name="question1" value="1"/> <br/>

	Playing computer games <input type="radio" name="question1" value="2"/> <br/>
	Reading books <input type="radio" name="question1" value="3"/> <br/>
        </p>
        <p>
	What do you prefer to do on Saturday nights ?  <br/>
	Staying at home <input type="radio" name="question2" value="1"/> <br/>

	Going out alone <input type="radio" name="question2" value="2"/> <br/>
	Inviting friends <input type="radio" name="question2" value="3"/> <br/>
	Going out with friends <input type="radio" name="question2" value="4"/> <br/>
        </p>
	<input type="submit" value="Hit me"/>
    </form>     
    
    <hr/>
  </body>
</html>

Live file: 2-xhtml-radio-buttons.html

  • In the head element, we load JavaScript code that defines a "give_feedback" function.
  • This give_feedback function is triggered when the user presses the submit button. This happens because we defined in the form tag the attribute onsubmit="give_feedback().

There a several ways of dealing with HTML forms. As we said above, code presented below can be called old style JavaScript programming, since it includes JavaScript code within the HTML form code.

 <form name="quiz" action="#" method="get" onsubmit="give_feedback()"> .... </form>

Below is the contents of the 2-xhtml-radio-buttons.js JavaScript file:

// Made by Daniel K. Schneider, TECFA, March 2008. This is freeware.
// Needs file 2-xhtml-radio-buttons.html

function give_feedback() {
  
  // f is variable that points to the form, just a shortcut
  var f = document.forms["quiz"];
    
  // ---------------- debugging --------------------
  // Let's provide some debugging information to the designer. 
  // Remove this section at some point or add other debugging information to print out
  // Information about the form and its current state can be retrieved by various properties
  info = "This alert provides some debugging info to remove at later stage:\n"
    + "f.elements: " + f.elements + "\n"
    + "f.elements[0]: " + f.elements[0] + "\n"
    + "f.elements[7]: " + f.elements[8] + "\n"
    + "f.length: " + f.length + "\n"
    + "f.onsubmit: " + f.onsubmit + "\n"
    + "f.name: " + f.elements + "\n"
    + "f.acceptCharset: " + f.acceptCharset + "\n"
    + "f.action: " + f.action + "\n"
    + "f.enctype: " + f.enctype + "\n"
    + "f.encoding: " + f.encoding + "\n"
    + "f.method: " + f.method + "\n"
    + "f.target: " + f.target + "\n"
    + "f.elements['question1'][0].checked:" + f.elements['question1'][0].checked + "\n"
    + "f.elements['question1'][1].checked:" + f.elements['question1'][1].checked + "\n"
    + "f.elements['question1'][2].checked:" + f.elements['question1'][2].checked + "\n"
    + "f.elements['question1'][0].value:" + f.elements['question1'][0].value + "\n"
    + "f.elements['question1'][1].value:" + f.elements['question1'][1].value + "\n"
    + "f.elements['question1'][2].value:" + f.elements['question1'][2].value + "\n";
  // show this information
  alert (info);				      
  
  // ---------------- Compute a score --------------------
  // Initially, score is 0
  var score = 0; 

  for (var i=0; i < (f.length); i++)  {
    // if the user selected a radio button it is checked
    // In this case we add its value to the score (see the HTML form)
    if (f.elements[i].checked)  {
      score = score + parseInt(f.elements[i].value);
    }
  }

  // ---------------- Provide feedback --------------------

  // Let's check if the user answered at least one question
  if (!score) {
    alert ("Hey you have to fill in at least something");
    return "lazy user";
  }

  // Now provide feedback
  // Of course, this is a rather dumb test ... as example code tends to be
  // If you plan to reuse this code, you certainly MUST change this
 
  if (score > 6) feedback = "Wow, you are a really active person"
  else if (score > 4) feedback = "You are quite an active person"
  else if (score > 3) feedback = "You are an active person"
  else feedback = "You are not too active";

  alert ("Here are some test results: " + feedback);
}

Understanding how to deal with HTML forms is not trivial, i.e. at some point you may have to learn about DOM and be able to understand texts like the Gecko HTML Form Interface documentation.

In our code we included a po-pup window that includes DOM information, i.e. it will tell how what DOM "sees" in the form elements.

You may remove the following line or even the whole debugging section. To do so, just quote line that displays the popup. Change:

  alert (info);

to

// alert (info);				      

For starters, you just may try to adapt code to your needs. So let's now explain a bit what the give_feedback() function does:

The following line will retrieve a handle on the form from the DOM

 // f is variable that points to the form, just a shortcut
 var f = document.forms["quiz"];

In other words the f variable now includes an object that represents the current state of the form and allows to retrieve various information.

The following code will loop through all form elements, i.e. all radio buttons. For each one it will first check if the the button is "check" (i.e. if the user clicked on it). If so it adds the value to the score variable which is initially set to zero.

  // ---------------- Compute a score --------------------
  // Initially, score is 0
  var score = 0; 

  for (var i=0; i < (f.length); i++)  {
    // if the user selected a radio button it is checked
    // In this case we add its value to the score (see the HTML form)
    if (f.elements[i].checked)  {
      score = score + parseInt(f.elements[i].value);
    }
  }

Once we computed the total score, we then first checked if the user answered at least one question. If he didn't then we complain and stop execution.

  // Let's check if the user answered at least one question
  if (!score) {
    alert ("Hey you have to fill in at least something");
    return "lazy user";
  }

The following code will provide feedback. The variable score holds the total score of the user. We then use a so-called if statement to provide differentiate feedback. You should notice that we start from the highest possible score if (score>6) and then provide feedback for intermediate scores e.g. else if (score > 3), before finally providing a feedback for all other cases.

  // Now provide feedback
  // Of course, this is a rather dumb test ... as example code tends to be
  // If you plan to reuse this code, you certainly MUST change this
 
  if (score > 6) feedback = "Wow, you are a really active person"
  else if (score > 4) feedback = "You are quite an active person"
  else if (score > 3) feedback = "You are an active person"
  else feedback = "You are not too active";

The syntax of an if statements goes like this:

if (condition) ..... 
 else if (condition2) .....
 else if (condition3) .....
 // etc.
 else .....

The feedback variable will hold the feedback string, that then is displayed with an alert widget.

 alert ("Here are some test results: " + feedback);

JavaScript new style

The 3-xhtml-radio-buttons.html example is nearly identical. The only difference is in the forms element.

<form id="quiz" action="#" method="get">  

The JavaScript code available in 3-xhtml-radio-buttons.js is also very similar. The big difference is that we will use some "init" code to link a JavaScript function with a user event.

// When the page loads the init function will be called
window.onload = init;

// Init code executed when the page loads
function init () {
  document.getElementById("quiz").onsubmit = give_feedback;
}

Dealing with checkboxes

Dealing with checkboxes is a bit more difficult. In the following example we introduce a combined HTML/JS page that shows how to deal with these.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
  <head>
    <title>XHTML form example</title>
    <meta http-equiv="Content-Type" content="text/html;charset=iso8859-1" />
    <script type="text/javascript" language="javascript">

    function give_feedback() {
      var f = document.forms["quiz"];
      info = "This alert shows what we can get from the form:\n"
      info += "Let's first look at the " + f.length + " elements of this form.\n";
      for (var i=0; i < (f.length); i++) {
        info += "Object " + i + ": " + f.elements[i] + " ";
        info += " [Name="    + f.elements[i].name  + "] ";
        info += " [Value="   + f.elements[i].value  + "] ";
        info += " [Checked=" + f.elements[i].checked  + "]\n";
      }
      info += "\nLet's see what we get when we get elements by name \n";
      info += "f.elements['color'] returns a list since we got several: "
           + f.elements['color'] + "\n";
      info += "f.elements['color'][0] returns the first element (red): " 
           + f.elements['color'][0] + "\n";
      info += "f.elements['color'][0].value gives the first object's value: "
           + f.elements['color'][0].value + "\n";
      info += "f.elements['color'][0].checked gives the first object's checked: " 
           + f.elements['color'][0].checked + "\n";
      info += "f.elements['red'] gives a single object 3 element : " 
           + f.elements['red'] + "\n";
      info += "f.elements['red'].value gives the object 3 element's value: " 
           + f.elements['red'].value + "\n";
      info += "f.elements['red'].checked gives the object 3 element's checked: " 
           + f.elements['red'].checked + "\n";
     alert (info);
     return false;
     }

    </script>
  </head>
  
  <body>
    <h1>XHTML form example</h1>

    <p>Below is a simple form with checkboxes, please fill it in.</p>

    <form name="quiz" action="#" method="get" onsubmit="give_feedback()"> 
        <p>
      Tick colors you like (take 1)
       <input type="checkbox" name="color" value="red"/>Red
       <input type="checkbox" name="color" value="blue"/>Blue
       <input type="checkbox" name="color" value="green"/>Green
         </p>
        <p>
      Tick colors you like (take 2):
       <input type="checkbox" name="red" />RED
       <input type="checkbox" name="blue" />BLUE
       <input type="checkbox" name="green" />GREEN

        </p>

	<input type="submit" value="Hit me"/>
     Repeat this with different answers and study the alert box. 
     Also watch the URL on top.
    </form>     
    
    <hr/>
  </body>
</html>

Live example: 5-xhtml-checkboxes.html

  • In the head, some JavaScript code that defines a "give_feedback" function is loaded
  • Checkboxes are a bit more difficult to handle than radio buttons. Also, unlike radio buttons you can either choose to differentiate between check boxes by either giving them the same name but different value combination or alternatively by giving each checkbox its own name.
  • In the first case you have to retrieve the element by an index, in the second you don't need to.
  • To decide if a user checked a checkbox, you need to look at the the "checked" property.

To understand this code, you have to study both the HTML markup of the input elements and then study the results of the debugging code shown.

Form validation

JavaScript is often used to validate forms, i.e. make sure that user fill in all the elements. You may find many form validation scripts on the Internet, some of which are listed in the JavaScript links entry in this wiki.

Below we present a simple example to validate radio and checkboxes input:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
  <head>
    <title>Validation of radio and check boxes input</title>
    <meta http-equiv="Content-Type" content="text/html;charset=iso8859-1" />
    <script type="text/javascript" language="javascript">

// will return false if nothing is checked or the selected value

function get_selected_radio_value (list) {
  var selection = false;
  
  for (i=0;i<list.length;i++) {
    //alert (list[i].checked + "-" + list[i].value);
    if (list[i].checked) {
      selection = list[i].value;
    }
  }
  return selection;
}

function give_feedback() {
  // f is a shortcut to the form
  var f = document.forms["quiz"];
  
  info = "This alert shows what we can get from the form:\n"
    
  info += "Let's first look at the " + f.length + " elements of this form.\n";
  
  // This loop will list all the form elements and add some information about each.
  for (var i=0; i < (f.length); i++) {
    info += "Object " + i + ": " + f.elements[i] + " ";
    info += " [Name="    + f.elements[i].name  + "] ";
    info += " [Value="   + f.elements[i].value  + "] ";
    info += " [Checked=" + f.elements[i].checked  + "]\n";
  }
  info += "\nLet's see what we get when we get elements by name \n";
  info += "f.elements['color'] returns a list of checkbox objects since we got several: " 
    + f.elements['color'] + "\n";
  info += "f.elements['color'].checked returns: " 
    + f.elements['color'].checked + "\n";
  info += "f.elements['color'][0] returns the first element (red): "
    + f.elements['color'][0] + "\n";
  info += "f.elements['color'][0].value gives the first object's value: "
    + f.elements['color'][0].value + "\n";
  info += "f.elements['color'][0].checked gives the first object's checked: " 
    + f.elements['color'][0].checked + "\n\n";
  
  info += "f.elements['metallicred'] returns a check box object: "  
    + f.elements['metallicred'] + "\n";
  info += "f.elements['metallicred'].value gives the object's value: "
    + f.elements['metallicred'].value + "\n";
  info += "f.elements['metallicred'].checked returns the object's checked: "
    + f.elements['metallicred'].checked + "\n\n";
  
  info += "get_selected_radio_value (f.elements['colorpref']) will return: "
    + get_selected_radio_value(f.elements['colorpref'])+ "\n\n"; ;
  
  info += "f.elements['colorselect'].value returns the select box checked value: "
    + f.elements['colorselect'].value + "\n\n";
  alert (info);
  return false;
}

function validate(f) {
  var feedback = "Please fill in all required elements !\n";
  var ok = true;

  if (!(f.elements['color'][0].checked||f.elements['color'][1].checked
        ||f.elements['color'][2].checked)) {
    ok = false;
    feedback+="Please select at least a color from the first color list! \n";
  }
  if (!(f.elements['metallicred'].checked||f.elements['metallicblue'].checked
        ||f.elements['metallicgreen'].checked)) {
    ok = false;
    feedback+="Please select at least a color for the metallic list! \n";
  }
  if (get_selected_radio_value(f.elements['colorpref'])==false){
    ok = false;
    feedback+="Please select a color from the radio buttons !\n";
  }
  if (f.elements['colorselect'].value=="noselect") {
    ok = false;
    feedback+="Please select a color from the pulldown menu !\n";
  }

  if (!ok) alert (feedback);
  // page should not reload
  return false;
}


    </script>
  </head>
  
  <body>
    <h1>Validation of radio and check boxes input</h1>

    <p>Below is a simple form with checkboxes and radio buttons, please fill it in.</p>

    <form name="quiz" action="#" method="get" 
          onsubmit="give_feedback();validate(this);"> 
        <p>
      Tick colors you like (each checkbox has same name)
       <input type="checkbox" name="color" value="red"/>Red
       <input type="checkbox" name="color" value="blue"/>Blue
       <input type="checkbox" name="color" value="green"/>Green
         </p>
        <p>
      Tick again colors you like (each checkbox as a different name):
       <input type="checkbox" name="metallicred" />Metallic red
       <input type="checkbox" name="metallicblue" />Metallic blue
       <input type="checkbox" name="metallicgreen" />Metallic green
        </p>

        <p>
      Select once more a color you like (radio buttons):
       <input type="radio" name="colorpref" value="red"/>Pastel red
       <input type="radio" name="colorpref" value="blue"/>Pastel blue
       <input type="radio" name="colorpref" value="green"/>Pastel green
        </p>
        <p>
      Select a color you like (select menu):
	<select name="colorselect">
	  <option value="noselect">--select--</option>
	  <option value="red">RED</option>

	  <option value="blue">BLUE</option>
	  <option value="green">GREEN</option>
	  <option value="yellow">YELLOW</option>
	</select>
        </p>
      <input type="submit" value="Hit me"/>
    </form>     
  </body>

</html>

Live code: 6-form-validation.html

  • In the head, some JavaScript code that defines a "give_feedback" function is loaded
  • To check if the user selected a radio-button to retrieve a selection value we wrote a little function. function get_selected_radio_value (list) will take a DOM node list representing a series of checkboxes.
function get_selected_radio_value (list) {
  var selection = false;
  
  for (i=0;i<list.length;i++) {
    //alert (list[i].checked + "-" + list[i].value);
    if (list[i].checked) {
      selection = list[i].value;
    }
  }
  return selection;
}

To test if someone picked a value from a color group we use code like:

 if (!(f.elements['color'][0].checked||f.elements['color'][1].checked
       ||f.elements['color'][2].checked)) { ....}

or like that (depending on how we defined the checkboxes in the HTML form)

 if (!(f.elements['metallicred'].checked||f.elements['metallicblue'].checked
    ||f.elements['metallicgreen'].checked)) { .... }

JavaScript exercise

Take the code from simple-quiz.html. This file includes both the HTML and the JavaScript code.

Make the following modifications:

(1) Change the contents of the radio buttons. I.e. ask two other questions and change the response items. You also may change the values (i.e. the scores in the form)

Which answer is correct ?
HTML forms are new <input type="radio" name="question1" value="0"/>
HTML forms are not well implemented <input type="radio" name="question1" value="1"/>
HTML forms work in any browser <input type="radio" name="question1" value="1"/>

(2) Add at least another question (3) Adapt the the conditions and the feedback in the if statement. E.g.

 if (score > 10) feedback = "You got a top score"
 else if (score > 8) feedback = "You are ....."
 else if (score > 6) feedback = "You are .... "
 else if (score > 4) feedback = "You are .... "
 else feedback = "You are .......";

Of course the conditions must be adapted to the scores a user may get

Do not forget:

  • To validate the HTML
  • To open an error console. It is likely that you make a JavaScript syntax mistake !

Links

See also our HTML links, JavaScript links and PHP links (includes tutorial links)

Tools

  • Form design guidelines crib sheet. A 1-page guideline for designing usable forms. Print it and stick it on your wall. “We’ve got the Omnigraffle original, PSD (Photoshop) and PDF examples for you to download and use how you wish. Print it out, stick it on your wall, send it to your clients, generally help make everybody’s forms better.” (nov 2011).

wikipedia

HTML references

(that include definitions of form elements)