working with forms. how are forms manipulated? the document object contains an array of forms...
TRANSCRIPT
Working with Forms
how are forms manipulated?
• the document object contains an array of forms objects, one for each form, in document order– forms[]
• any form is referenced through this array– e.g. the first form in a web page would be refeerenced
as document.forms[0]
• forms can also be referenced by NAME attribute– this makes programming easier
how are forms manipulated?
• form elements (the widgets) are accessed through the form’s elements array– e.g. document.forms[0].elements[1]– refers to the second element in the first form in
a document
• other properties of a form relate to HTML attributes– action, encoding , method, target
structure of a forms application
web page
document head
document body
functions
form
elements
one or more forms defined by HTML tags in the document body.
Each form contains elements such as text
fields and buttons.
form processing functions
functions and forms
• functions read values from form elements
• function parameters can be– element values– elements– forms
• re-useable validation functions can be imported from an external script file
external script files
• contain arbitrary JavaScript code
• usually used to define re-useable functions– form validation– boilerplate HMTL
• code is maintained in one place, used in many pages
• imported using the SCRIPT tag
Example
<SCRIPT LANGUAGE = "JavaScript" SRC = ”myScript.js"></SCRIPT>
myScript.jsany web
page
embedded
what are forms used for?
• providing a client-side user interface– input through prompt boxes, text fields and text
areas– output through text fields and text areas, pop-
up windows, HTML text elements– control through buttons and hyperlinks
• collecting data to send to a server process– the data from a single form is submitted
Simple Interface Example
Example
Example
<HTML><HEAD><TITLE> The Multiplier</TITLE><SCRIPT LANGUAGE = "JavaScript1.1">
//form processing functionalityfunction multiply(){ //read the numbers from the form fields x = document.multiplier.num1.value; y = document.multiplier.num2.value; // compute and output the product product = x * y; alert(x);}</SCRIPT></HEAD>
Example...<BODY><H1>The Multiplier</H1>Please input a number in each box...<HR><FORM NAME = ”multiplier"><INPUT TYPE="text" NAME=”num1” SIZE="3">* <INPUT TYPE="text" NAME=”num2" SIZE="3"> <INPUT TYPE="button" ONCLICK=”multiply()" VALUE="Answer!"></FORM><HR></BODY></HTML>
Extended Exampleclient-side forms interface
Requirements
• a simple web interface to try out text and background colour combinations for web page design
• user defines colours, web page displays a sample table layout using those colours
Design
• frameset with two frames– colour picker frame– display frame
• function in an externally defined script– re-useable for colouring other framesets
• button in colour picker frame to trigger the display function
• form with text fields used for input
top-level frameset
<HTML><HEAD><TITLE>Colour Picker</TITLE></HEAD>
<FRAMESET ROWS = "50%,*"><FRAME NAME = "topOne" SRC ="cols.html"><FRAME NAME = "botOne" SRC ="blank.html"></FRAMESET></HTML>
colour-picker frame
<HTML><HEAD><SCRIPT
LANGUAGE = "JavaScript” SRC = "picker.js"></SCRIPT></HEAD><BODY BGCOLOR = "white" TEXT = "red"><H1 ALIGN = "CENTER">Colour Picker</H1><!-- continued on next slide -->
colour-picker frame
<FORM><TABLE ALIGN = "CENTER" BORDER = "0" CELLPADDING = "5">
<TR><TD COLSPAN = "4" ALIGN = "CENTER"><H2>Enter colour values in the boxes</H2></TD></TR><!-- now add the form elements -->
colour-picker frame
<TR><TD><H3>Background Colour</H3></TD><TD><INPUT TYPE = "TEXT” NAME = "bgcol"></TD><TD><H3>Text Colour</H3></TD><TD><INPUT TYPE = "TEXT" NAME = "fgcol" VALUE = "black"></TD>
</TR><TR><TD><H3>Table Headings</H3></TD><TD><INPUT TYPE = "TEXT" SIZE = "16" NAME = "thcol" VALUE = "black"></TD>
<TD> <H3>Table Data</H3></TD><TD> <INPUT TYPE = "TEXT" SIZE = "16" NAME = "tdcol" VALUE = "black"></TD></TR>
colour-picker frame
<TR><TD COLSPAN = "4" ALIGN = "CENTER"><INPUT
TYPE = "BUTTON”VALUE = "Show It!!”ONCLICK = "showIt ();”
></TD></TR>
</TABLE></BODY></HTML>
picker.js
function showIt () {//get the array of text fieldsvar topBox = document.forms [0].elements;
//get hold of the document to write to//and give it a managable namevar bottomBox = parent.frames['botOne'].document;
picker.js
// now extract the values from the form elements
var bg = topBox.bgcol.value;var fg = topBox.fgcol.value;var thc = topBox.thcol.value;var tdc = topBox.tdcol.value;
picker.js
// now build the new page, using these colour variables
bottomBox.open ();bottomBox.write("<BODY BGCOLOR = " + bg + " TEXT = " + fg + ">\n");
bottomBox.write ("<H1 ALIGN = CENTER> The Result Is:</H1>");
picker.js
bottomBox.write ("<TABLE ALIGN = CENTER BORDER = 2 CELLPADDING = 4 CELLSPACING = 4>\n<TR>");
bottomBox.write ("<TH>Plain Heading</TH>");bottomBox.write ("<TH BGCOLOR = " + thc + ">Coloured Heading</TH>");bottomBox.write ("</TR><TR>");bottomBox.write ("<TD>Plain Data</TD>");bottomBox.write ("<TD BGCOLOR = " + tdc + ">Coloured Data</TD>");bottomBox.write ("</TR>\n</TABLE></BODY>");bottomBox.close ();
}
Form Validation
form validation
• client-side validation checks form data before submission to server processes
• reduces input errors
• saves communication time
• easier to correct errors on input
• reduces error-processing overhead on the web server
typical form validation checks
• check all required fields have been completed
• check all numerical values are in range
• check coded data are in an appropriate format– post codes– telephone numbers– credit card numbers
• Luhn’s algorithm
form validation techniques
• validation checks are encoded as JavaScript functions– run onSubmit or in response to other events– standard functions imported from external scripts
• functions read form elements and perform tests
• assign new properties to form elements to assist validation– e.g. numerical ranges, boolean properties
limits of client-side validation
• web pages can be “spoofed”
• validation code is visible in the page source and can be altered
• reduces errors but does not prevent malicious input of false (or dangerous) data
• data should always be re-validated on the server
Extended Example:Form Validation
Requirements
• personal information form– name, address, zip code, phone number
• first name and phone number optional, all other fields must be completed
• zip code must be within min and max value
• error message should indicate– which non-optional fields are blank– which numerical fields are out of range
• validation function should be re-useable
Design
• function isBlank returns a boolean indicating whether a field is blank– should work on a text field or a textarea
• function verify runs when a form is submitted– checks all fields in the form– submits data if all fields valid– blocks invalid data and produces a list of errors
Design
• import verify and isBlank as external scripts– they can be re-used on other pages and
maintained in the one script file
• attach verify to the onSubmit event-handler on the form
• add validation properties to particular form elements
<FORM onSubmit = "this.firstName.optional = true;this.phoneNumber.optional = true;this.zip.min = 0; this.zip.max = 99999;return verify (this);">
First Name: <INPUT TYPE = "text" NAME = "firstName">
Last Name: <INPUT TYPE = "text" NAME = "lastName">
Address: <TEXTAREA NAME = "address" ROWS = "4" COLS = "40"></TEXTAREA>
Zip Code: <INPUT TYPE = "text" NAME = "zip">
Phone Number: <INPUT TYPE = "text" NAME = "phoneNumber">
<INPUT TYPE = "submit"></FORM>
function isBlank (s) {// accepts a string as input// the string will come from a form// element for (var i = 0; i < s.length; i++) { //check each character var c = s.charAt (i); if ((c != ' ') && (c != '\n') && (c != '\t')) //the element is not blank
return false;}
// all chars are whitespacereturn true;
}
function verify (f) { var msg; var emptyFields = ""; var errors = ""; // loop through form elements for (var i = 0; i < f.length; i++) { var e = f.elements [i]; // look for text fields and text areas if (((e.type == "text") || (e.type == "textarea")) && !e.optional) {
// look for empty fields if ((e.value == null) || (e.value == "") ||
isBlank(e.value)) {emptyFields += "\n " + e.name;
continue;}
// check max and min values for numeric fieldsif (e.numeric || (e.min != null) || (e.max != null)) { var v = parseFloat (e.value); if (isNaN (v) || ((e.min != null) && (v < e.min)) ||
((e.max != null) && (v > e.max))) {errors += "- The field " + e.name +
" must be a number"; if (e.min != null) errors += " that is greater than " + e.min; if (e.max != null && e.min != null)
errors += " and is less than " + e.max; else if (e.max != null)
errors += " that is less than " + e.max; errors += ".\n"; } }
} } if ((errors) || (emptyFields)){
// display error messages
msg = "___________________________________\n\n";msg += "The form was not submitted.\n";msg += "Please correct errors and resubmit.\n";msg +="__________________________________\n\n";
if (emptyFields) { msg += "-The following fields are empty:" +
emptyFields + "\n"; if (errors) msg += "\n";}msg += errors;alert (msg);return false;}return true;}