HTML forms tutorial: Difference between revisions
mNo edit summary |
mNo edit summary |
||
Line 121: | Line 121: | ||
</body> | </body> | ||
</html> | </html> | ||
</source> | </source> | ||
Line 171: | Line 170: | ||
=== AJAX === | |||
The Ajax technique uses 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. | |||
=== Processing forms with PHP === | === Processing forms with PHP === | ||
Line 211: | Line 218: | ||
'''Contents of the Php file''' | '''Contents of the Php file''' | ||
<source lang="PHP"> | |||
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> | ||
<html><head><title>Simple test with</title></head><body> | <html><head><title>Simple test with</title></head><body> | ||
<h1>Simple test with PHP</h1><hr> | <h1>Simple test with PHP</h1><hr> | ||
<?php | |||
// Get variables from the form | // Get variables from the form | ||
$choice = $_POST['choice']; | |||
$choice2 = $_POST['choice2']; | |||
// Compute the score | // Compute the score | ||
$score = $choice + $choice2; | $score = $choice + $choice2; | ||
// Display the score | // Display the score | ||
echo "<h3>Your score is " . $score . "</h3>"; | |||
if ($score < 3) { | if ($score < 3) { | ||
echo "<p>You are a beginner</p>"; | echo "<p>You are a beginner</p>"; | ||
Line 231: | Line 239: | ||
echo "<p>You are an expert !</p>"; | echo "<p>You are an expert !</p>"; | ||
} | } | ||
?> | |||
<hr>DKS - 2007 | <hr>DKS - 2007 | ||
</body></html> | </body></html> | ||
</source> | |||
No need to understand CGI details, PHP makes it quite easy .... | |||
=== 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. | |||
;MAMP means | |||
: Windows, the operating system; | : Windows, the operating system; | ||
: Apache, the Web server; | : Apache, the Web server; | ||
: MySQL, the database management system | : MySQL, the database management system | ||
: PHP | : PHP | ||
The | == 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". | |||
<source lang="xml"> | |||
<!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> | |||
</source> | |||
Live file: [http://tecfa.unige.ch/guides/js/ex/coap/week-3/2-xhtml-radio-buttons.html 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 because in the form tag we defined the attribute <code>onsubmit="give_feedback()</code>. | |||
There a several ways of dealing with HTML forms. Code presented below can be called '''old style''' JavaScript programming, since it includes JavaScript code within the ''form'' HTML code. | |||
<form name="quiz" action="#" method="get" onsubmit="give_feedback()"> .... </form> | |||
Below is the contents of the [http://tecfa.unige.ch/guides/js/ex/coap/week-3/2-xhtml-radio-buttons.js 2-xhtml-radio-buttons.js] JavaScript file: | |||
<source lang="javascript"> | |||
// 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); | |||
} | |||
</source> | |||
* Understanding how to deal with HTML forms is not trivial, i.e. you have to learn about DOM and be able to understand texts like the [[http://developer.mozilla.org/en/docs/DOM:form">Gecko HTML Form Interface documentation]]. | |||
* In our code we included a popup window that includes DOM information. You may remove the following line or even the whole debugging section. | |||
alert (info); | |||
* However, for starters, you just may try to adapt code to your need. | |||
=== JavaScript new style === | |||
The [http://tecfa.unige.ch/guides/js/ex/coap/week-3/3-xhtml-radio-buttons.html 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 [http://tecfa.unige.ch/guides/js/ex/coap/week-3/3-xhtml-radio-buttons.js 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. | |||
<source lang="javascript"> | |||
// 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; | |||
} | |||
</source> | |||
=== Dealing with checkboxes === | |||
Dealing with checkboxes is a bit more difficult. In the following example with introduce a combined HTML/JS page that shows how to deal with these. | |||
<source lang="xml"> | |||
<!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> | |||
</source> | |||
* 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. | |||
Revision as of 14:07, 4 October 2009
This article or section is currently under construction
In principle, someone is working on it and there should be a better version in a not so distant future.
If you want to modify this page, please discuss it with the person working on it (see the "history")
<pageby nominor="false" comments="false"/>
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
- HTML and XHTML elements and attributes
- See also: HTML and XHTML for some background information and HTML links for a page with pointers (e.g. to other HTML tutorials)
- Concurrent
- Moving on
- See the list of web technology tutorials
- Level and target population
- Beginners
- 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.
- To do: Add some more tags and attributes, some additional explantions for each tag, an HTML forms tutorial, etc.
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: Switzeland</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
Forms processing with the Common Gateway Interface
HTML forms can be processed by a webserver in two ways, either trough the older, easier and still more popular CGI Interface or with 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 program identified by the URL, e.g. a PHP file.
HTTP
- Hypertext Transfer Protocol (HTTP) is a communications protocol used to transfer or convey information on the World Wide Web. (Wikipedia). These messages have two parts
- Information that the user will not see
- 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 ....
CGI Principles
AJAX
The Ajax technique uses 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.
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:
- HTML files are just sent to the browser
- PHP files are executed by the web server and only the result (which usually is some HTML code) is then sent to the browsers.
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 ..... ?>
<?php echo("I am a php instruction\n"); ?>
Example
- calculate.html and calculate.php (but these files need to be put on a server)
The HTML form:
<form '''action="calculate.php"''' '''method="post"'''>
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>
Contents of the Php file
<!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><hr>
<?php
// Get variables from the form
$choice = $_POST['choice'];
$choice2 = $_POST['choice2'];
// Compute the score
$score = $choice + $choice2;
// Display the score
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>";
}
?>
<hr>DKS - 2007
</body></html>
No need to understand CGI details, PHP makes it quite easy ....
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.
- MAMP means
- 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".
<!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 because in the form tag we defined the attribute
onsubmit="give_feedback()
.
There a several ways of dealing with HTML forms. Code presented below can be called old style JavaScript programming, since it includes JavaScript code within the form HTML 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. you have to learn about DOM and be able to understand texts like the [">Gecko HTML Form Interface documentation].
- In our code we included a popup window that includes DOM information. You may remove the following line or even the whole debugging section.
alert (info);
- However, for starters, you just may try to adapt code to your need.
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 with 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>
- 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.