HTML forms tutorial: Difference between revisions

The educational technology and digital learning wiki
Jump to navigation Jump to search
mNo edit summary
 
(46 intermediate revisions by 2 users not shown)
Line 1: Line 1:
{{under construction}}
{{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: Add some more tags and attributes, some additional explantions for each tag, an HTML forms tutorial, etc.
* 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 66: Line 68:
<strong>Countries I visited</strong>
<strong>Countries I visited</strong>
<select name="country" size=1>
<select name="country" size=1>
  <option>CH:  Switzeland</option>
  <option>CH:  Switzerland</option>
  <option>D:  Germany</option>
  <option>D:  Germany</option>
  <option>F:  France</option>
  <option>F:  France</option>
Line 126: Line 128:
[[image:html-form-example.png|thumb|300px|right|HTML form example]]
[[image:html-form-example.png|thumb|300px|right|HTML form example]]
This example demoes the most important HTML forms elements.
This example demoes the most important HTML forms elements.
HTML forms all must be children of the <code>form</form> element and which has the following syntax:
HTML forms all must be children of the <code><form>....</form></code> element and which usually is used in the following way:
<source lang="xml">
<source lang="xml">
  <form name="myform" action="#" method="get">
  <form name="myform" action="#" method="get">
Line 135: Line 137:
* the ''method'' attribute defines which of the HTTP methods is being used, usually "GET" or "POST" (see below).
* 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.
* 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 ===


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 ===
=== 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:
<source lang="HTML5">
<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>
</source>
====Select attributes====
'''Autofocus''': Gives focus to the drop-down list when the page is loaded
<source lang="HTML5">
<select autofocus>
  <option value="2011">2011</option>
  <option value="2012">2012</option>
  <option value="2013">2013</option>
  <option value="2014">2014</option>
</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/>
'''Disabled''': Specifies that the drop-down list is being disabled
<source lang="HTML5">
<select disabled>
  <option value="2011">2011</option>
  <option value="2012">2012</option>
  <option value="2013">2013</option>
  <option value="2014">2014</option>
</select>
</source>
'''Form''': Specifies the forms in which the selected field belongs to
<source lang="HTML5">
<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>
</source>
'''Note''': The form attribute is not supported in Internet Explorer.
'''Multiple''': multiple options can be selected at once
<source lang="HTML5">
<select multiple>
  <option value="2011">2011</option>
  <option value="2012">2012</option>
  <option value="2013">2013</option>
  <option value="2014">2014</option>
</select>
</source>
'''Name''': Name of drop-down list
<source lang="HTML5">
<select name="years">
  <option value="2011">2011</option>
  <option value="2012">2012</option>
  <option value="2013">2013</option>
  <option value="2014">2014</option>
</select>
</source> 
'''Size''': the number of visible options in a drop-down list
<source lang="HTML5">
<select size="3">
  <option value="2011">2011</option>
  <option value="2012">2012</option>
  <option value="2013">2013</option>
  <option value="2014">2014</option>
</select>
</source>
'''Note''': In Chrome and Safari, this attribute may not work as expected for size="2" and size="3".<br /><br />
see more: http://www.w3schools.com/tags/tag_select.asp


=== Text area element ===
=== Text area element ===


The text area allows users to enter larger text. This element is also used for programming [[through the web editor]]s.
Example:
Tell me anything you want to ...
<textarea name="comments" rows=4 cols=60></textarea>


== Forms processing with the Common Gateway Interface ==
== Server-side forms processing ==


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]]
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 program identified by the URL, e.g. a PHP file.
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 ===
=== HTTP ===
Line 155: Line 282:
The Hypertext Transfer Protocol (HTTP) is a communications protocol used to transfer or convey information on the World Wide Web. (Wikipedia).  
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 roundtrip from browser to server and back can be explained with the following picture:
In the most simple case, a HTTP round trip from browser to server and back can be explained with the following picture:
[[image:HTTP-request-return.png|frame|none|A simple HTTP request and answer]]
[[image:HTTP-request-return.png|frame|none|A simple HTTP request and answer]]


Message sent from browser to server and the other way round have two parts
Messages sent from browser to server and the other way round have two parts
# Information that the user will not see
# Information that the user will not see
# Data
# Data
Line 192: Line 319:
   .... Contents, e.g. HTML code ....
   .... Contents, e.g. HTML code ....


=== CGI Principles ===
=== Request methods, server-side scripts and database ===


The common gateway interface defines how a web server can deal with HTML forms. From an HTML form, forms data can be sent to a web server as the following picture shows:
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.


[[image:HTTP-forms-submission.png|frame|none|Forms submission with HTTP]]
[[image:HTTP-forms-submission.png|frame|none|Forms submission with HTTP]]


In addition, the script then often will "talk" to a database as the following picture shows:
; 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 [http://en.wikipedia.org/wiki/Url_encoding Wikipedia], the list of reserved characters that must be specially encoded is show in the following table:
 
{| cellpadding="6px" border=1 style="border:1px solid #C0C0C0; border-collapse:collapse; background-color:#FFFFFF;"
|+ Reserved characters after percent-encoding
|-
|<nowiki>!</nowiki>||<nowiki>*</nowiki>||"||'||(||)||;||:||@||<nowiki>&</nowiki>||=||+||$||,||/||?||%||#||[||<nowiki>]</nowiki>
|-
|%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:


[[image:HTTP-forms-submission2.png|frame|none|Forms submission with HTTP and databases]]
[[image:HTTP-forms-submission2.png|frame|none|Forms submission with HTTP and databases]]


=== Web development ===


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


The Ajax technique uses a combination of:
[[image:three-tier-web-architecture.png|frame|none|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.
: XHTML (or HTML) and CSS, for marking up and styling information.
: The DOM accessed with a client-side scripting language, usually ECMAScript (JavaScript)
: 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.
: 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.
: 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 ===
=== 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:
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
* When the user requests and HTML file, it is just delivered to the browser as is.
* PHP files are executed by the web server and only the result (which usually is some HTML code) is then sent to the browsers.
* 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 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 code is inserted between: '''<?php ..... ?>'''. Make sure not remove any of these "XML processing instruction" tags.


  <?php echo("I am a php instruction\n"); ?>
  <?php echo("I am a php instruction\n"); ?>
Comments are inserted after ''//''.


'''Example'''
'''Example'''


: '''calculate.html and calculate.php (but these files need to be put on a server)'''
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]].
 
<source lang="xml">
<!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:


The HTML form:
<hr>


<source lang="xml">
<form action="quiz-processing.php" method="post">
  <form '''action="calculate.php"''' '''method="post"'''>
 
Please enter your name:
  <input type="text" name="username">


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


  <br>
  <br/>
  What is your programming experience ?
  What is your programming experience ?
  <input type="radio" name="choice2" value="1" checked>none
  <input type="radio" name="choice2" value="1" checked>none
Line 245: Line 431:
  <P>
  <P>
  <input type="submit" value="See result!">
  <input type="submit" value="See result!">
</form>


</form>
</body>
</html>
</source>
</source>


'''Contents of the Php file'''
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.


<source lang="PHP">
<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>
       <h1>Simple test with PHP</h1><hr>
    <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
   <?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
   // Get variables from the form
   $choice = $_POST['choice'];
   $choice = $_POST['choice'];
   $choice2 = $_POST['choice2'];
   $choice2 = $_POST['choice2'];
  $user    = $_POST['username'];


   // Compute the score
   // Compute the score
   $score = $choice + $choice2;
   $score = $choice + $choice2;
   // Display the score
   // Display the score
  echo "Hi $user. Thanx for filling in the form.";
   echo "<h3>Your score is " . $score . "</h3>";
   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 272: Line 476:
     echo "<p>You are an expert !</p>";
     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
   <hr>DKS - 2007
   </body></html>
   </body>
</html>
</source>
</source>
No need to understand CGI details, PHP makes it quite easy ....


=== Playing at home ===
=== 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.
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
; LAMP/WAMP means
: Windows, the operating system;
: '''L'''inux or '''W'''indows, the operating system;
: Apache, the Web server;
: Apache, the Web server;
: MySQL, the database management system
: MySQL, the database management system
: PHP  
: PHP


== Forms processing with JavaScript ==
== 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).
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".
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.


<source lang="xml">
<source lang="xml">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!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">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
   <head>
   <head>
Line 336: Line 550:


* In the head element, we load JavaScript code that defines a "give_feedback" function.
* 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>.
* This ''give_feedback function'' is triggered when the user presses the submit button. This happens because we defined in the ''form'' tag 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.
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>
   <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:
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:


Line 410: Line 625:
</source>
</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]].
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 [https://developer.mozilla.org/en/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);        
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.  
* However, for starters, you just may try to adapt code to your need.
 
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.
<source lang="javascript">
  // ---------------- 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);
    }
  }
</source>
 
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.
<source lang="javascript">
  // 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";
  }
</source>
 
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 <code>if (score>6)</code> and then provide feedback for intermediate scores e.g. <code>else if (score > 3)</code>, before finally providing a feedback for all other cases.
<source lang="javascript">
  // 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";
</source>
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 ===
=== JavaScript new style ===
Line 435: Line 706:
Dealing with checkboxes is a bit more difficult. In the [http://tecfa.unige.ch/guides/js/ex/coap/week-3/5-xhtml-checkboxes.html following example] we introduce a combined HTML/JS page that shows how to deal with these.
Dealing with checkboxes is a bit more difficult. In the [http://tecfa.unige.ch/guides/js/ex/coap/week-3/5-xhtml-checkboxes.html following example] we introduce a combined HTML/JS page that shows how to deal with these.
<source lang="xml">
<source lang="xml">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!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">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
   <head>
   <head>
Line 453: Line 725:
       }
       }
       info += "\nLet's see what we get when we get elements by name \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'] returns a list since we got several: "
       info += "f.elements['color'][0] returns the first element (red): " + f.elements['color'][0] + "\n";
          + f.elements['color'] + "\n";
       info += "f.elements['color'][0].value gives the first object's value: " + f.elements['color'][0].value + "\n";
       info += "f.elements['color'][0] returns the first element (red): "  
       info += "f.elements['color'][0].checked gives the first object's checked: " + f.elements['color'][0].checked + "\n";
          + f.elements['color'][0] + "\n";
       info += "f.elements['red'] gives a single object 3 element : "   + f.elements['red'] + "\n";
       info += "f.elements['color'][0].value gives the first object's value: "
       info += "f.elements['red'].value gives the object 3 element's value: "   + f.elements['red'].value + "\n";
          + f.elements['color'][0].value + "\n";
       info += "f.elements['red'].checked gives the object 3 element's checked: "   + f.elements['red'].checked + "\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);
     alert (info);
     return false;
     return false;
Line 488: Line 767:


<input type="submit" value="Hit me"/>
<input type="submit" value="Hit me"/>
     Repeat this with different answers and study the alert box. Also watch the URL on top.
     Repeat this with different answers and study the alert box.  
    Also watch the URL on top.
     </form>     
     </form>     
      
      
Line 495: Line 775:
</html>
</html>
</source>
</source>
Live exemple: [http://tecfa.unige.ch/guides/js/ex/coap/week-3/5-xhtml-checkboxes.html 5-xhtml-checkboxes.html]
Live example: [http://tecfa.unige.ch/guides/js/ex/coap/week-3/5-xhtml-checkboxes.html 5-xhtml-checkboxes.html]


* In the head, some JavaScript code that defines a "give_feedback" function is loaded
* In the head, some JavaScript code that defines a "give_feedback" function is loaded
Line 506: Line 786:
=== Form validation ===
=== 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.
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 [http://tecfa.unige.ch/guides/js/ex/coap/week-3/6-form-validation.html example to validate radio and checkboxes input]:
Below we present a simple [http://tecfa.unige.ch/guides/js/ex/coap/week-3/6-form-validation.html example to validate radio and checkboxes input]:


<source lang="xml">
<source lang="xml">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!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">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
   <head>
   <head>
Line 579: Line 860:
   var ok = true;
   var ok = true;


   if (!(f.elements['color'][0].checked||f.elements['color'][1].checked||f.elements['color'][2].checked)) {
   if (!(f.elements['color'][0].checked||f.elements['color'][1].checked
        ||f.elements['color'][2].checked)) {
     ok = false;
     ok = false;
     feedback+="Please select at least a color from the first color list! \n";
     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)) {
   if (!(f.elements['metallicred'].checked||f.elements['metallicblue'].checked
        ||f.elements['metallicgreen'].checked)) {
     ok = false;
     ok = false;
     feedback+="Please select at least a color for the metallic list! \n";
     feedback+="Please select at least a color for the metallic list! \n";
Line 610: Line 893:
     <p>Below is a simple form with checkboxes and radio buttons, please fill it in.</p>
     <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);">  
     <form name="quiz" action="#" method="get"  
          onsubmit="give_feedback();validate(this);">  
         <p>
         <p>
       Tick colors you like (each checkbox has same name)
       Tick colors you like (each checkbox has same name)
Line 642: Line 926:
         </p>
         </p>
       <input type="submit" value="Hit me"/>
       <input type="submit" value="Hit me"/>
    Repeat this with different answers and study the alert box. Also watch the URL on top.
     </form>     
     </form>     
   
    <hr/>
   </body>
   </body>


</html>
</html>
</source>
Live code: [http://tecfa.unige.ch/guides/js/ex/coap/week-3/6-form-validation.html 6-form-validation.html]
Live code: [http://tecfa.unige.ch/guides/js/ex/coap/week-3/6-form-validation.html 6-form-validation.html]


Line 654: Line 936:
* To check if the user selected a radio-button to retrieve a selection value we wrote a little function. <code>function get_selected_radio_value (list)</code> will take a DOM node list representing a series of checkboxes.
* To check if the user selected a radio-button to retrieve a selection value we wrote a little function. <code>function get_selected_radio_value (list)</code> will take a DOM node list representing a series of checkboxes.
<source lang="javascript">
<source lang="javascript">
function get_selected_radio_value (list) {
function get_selected_radio_value (list) {
   var selection = false;
   var selection = false;
Line 669: Line 950:


To test if someone picked a value from a color group we use code like:
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)) {
<source lang="javascript">
or
  if (!(f.elements['color'][0].checked||f.elements['color'][1].checked
  (!(f.elements['metallicred'].checked||f.elements['metallicblue'].checked||f.elements['metallicgreen'].checked))
      ||f.elements['color'][2].checked)) { ....}
</source>
or like that (depending on how we defined the checkboxes in the HTML form)
<source lang="javascript">
  if (!(f.elements['metallicred'].checked||f.elements['metallicblue'].checked
    ||f.elements['metallicgreen'].checked)) { .... }
</source>
</source>
=== JavaScript exercise ===
Take the code from [http://tecfa.unige.ch/guides/js/ex/coap/week-3/simple-quiz.html 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)
  <p>
  Which answer is correct ? <br/>
  HTML forms are new <input type="radio" name="question1" value="0"/> <br/>
  HTML forms are not well implemented <input type="radio" name="question1" value="1"/> <br/>
  HTML forms work in any browser <input type="radio" name="question1" value="1"/> <br/>
  </p>
(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 ===
* [http://www.cxpartners.co.uk/cxblog/form_design_guidelines_crib_sheet_free/ Form design guidelines crib sheet]. A 1-page guideline for designing usable forms. Print it and stick it on your wall. {{quotation|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 ===
* [http://en.wikipedia.org/wiki/Percent-encoding Percent encoding]
* [http://en.wikipedia.org/wiki/Common_Gateway_Interface Common Gateway Interface]
* [http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol Hypertext Transfer Protocol]
* [http://en.wikipedia.org/wiki/XMLHttpRequest XMLHttpRequest]
* [http://en.wikipedia.org/wiki/Web_server Web server]
=== HTML references ===
(that include definitions of form elements)
* [http://reference.sitepoint.com/html/form form] (Sitepoint)
* [http://reference.sitepoint.com/html/elements-form form elements] (Sitepoint)
* [http://htmldog.com/reference/htmltags/form/ form] (HTML Dog)
[[Category:Web authoring]]

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)