1. Trang chủ
  2. » Công Nghệ Thông Tin

JavaScript 1.5 - Lab 6 pot

40 239 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 40
Dung lượng 558,21 KB

Nội dung

In the first few lines of the validateForm function, define the variables submitform = true, reqChar = “_”, and currElement.. The first statement in the if block must set currentElement

Trang 1

Regular Expressions and the RegExp Object

Lab 6:

Built-In Objects

TIP: Because this lab includes a great deal of typed code, we‘ve tried to make it

simpler for you You will find all the completed code in ValidateMe.html and ValidateMe.js, in the same directory as the sample project To avoid typing the code, use the exercise specific js files ValidateMe_ex1.js, for exercise one, and ValidateMe_.ex2.js and ValidateMe_ex3.js respectively Once you have completed each part, rename it ValidateMe.js to test it

Trang 2

Lab 6 Overview

In this lab you will learn to properly access various form elements, and how to validate values

To complete this lab, you will need to work through three exercises:

 Terminal: Routing and Setup

 Defining Validations

 Display Results Each exercise includes an ―Objective‖ section that describes the purpose of the exercise You are encouraged to try to complete the exercise from the

information given in the Objective section If you require more information to complete the exercise, the Objective section is followed by detailed step-by-step instructions

Trang 3

Terminal: Routing and Setup

Terminal: Routing and Setup

Objective

In this exercise, you will use a decision construct to direct different form elements to the appropriate validation function

Things to Consider

 The type property for a select object returns as ‗select-one‘

 Text objects and Textarea objects can be validated similarly

 You cannot return the length property of a radio group accurately from the form.elements[] array The reason is that when you call length on a single radio object, it always returns null

 The onSubmit() event handler of the form accepts a Boolean value indicating whether or not to process the submit request

Step-by-Step Instructions

1 You will be using the form found in the ValidateMe.html file It would be

helpful to glance through this file before you start the exercise, and take note of a few things within the file:

The file will look for the external js file, ValidateMe.js

The onsubmit event of form1 calls the function

validateForm(), which serves as the main function of this

function validateForm(frm) { }

Trang 4

3 In the first few lines of the validateForm() function, define the variables

submitform = true, reqChar = “_”, and currElement

NOTE The submitform variable will ultimately determine whether the

form is submitted or not The reqChar variable represents the first character in the name of a required field on the form The script, when complete, will know to look for this character to make sure that that current object has a value Finally, the currElement variable represents the current element in any iteration of the

forms.elements[] array This is important to note, because when

the ElementLoop is stopped because of a validation error, the

currElement will hold the information about the object that was

var submitform = true;

5 Within the loop block, create an if block The purpose of the if block will

be to catch only those elements that have the reqChar as the character at the first position in the string (charAt(0)), and to ignore any undefined

elements (like the fieldset object)

Trang 5

Terminal: Routing and Setup

ElementLoop:

for (fo = 0; fo < frm.elements.length; fo++) {

if (frm.elements[fo].name != undefined &&

frm.elements[fo].name.charAt(0) == reqChar) { //Then this is an element to be validated }

}

6 The first statement in the if block must set currentElement to reference

the currently selected form element in the iteration

if (frm.elements[fo].name != undefined &&

frm.elements[fo].name.charAt(0) == reqChar) {

currElement = frm.elements[fo];

7 On the next line, create a switch block with four cases, and no default

block The switch condition will be (currElement.type) The cases

represent the element types that you want to validate For this exercise

they will be as follows: case “select-one”, case “radio”, case “text”, and

case “textarea” Be sure to add a break; statement to each case

if (frm.elements[fo].name != undefined &&

frm.elements[fo].name.charAt(0) == reqChar) { currElement = frm.elements[fo];

switch(currElement.type) { case "select-one":

Trang 6

8 Right before the end of the main elements loop, add another if block with

the statement if (!submitform) { break ElementLoop; } This ensures

that if an element does not evaluate to true, then the loop will stop iterating

case "textarea":

break;

} }

if (!submitform) { break ElementLoop;

}

9 Underneath the main function, define the validation utility functions There will be a validation function for each type of object caught by the

switch statement in validateForm Each one will accept a frmobj, which

is also the currElement of the form Name the functions valSelect(),

valRadio(), and valText()

function valSelect(frmobj) { }

function valRadio(frmobj) { }

function valText(frmobj) { }

10 One thing that each function has in common is a Boolean variable called

valid Start by defining valid as false; each function will eventually return

the valid variable

Trang 7

Terminal: Routing and Setup

11 In the validateForm() function, each case is going to be nearly identical

Each one will define submitform using its corresponding utility function For example, case ―select-one‖ will define submitform by assigning it the return value of the function varSelect(currElement)

NOTE The one exception to the rule is case ―radio‖ When the element in

question is a radio button, currElement actually references an

individual radio button object The default value of an individual radio button‘s length is null In this application, you just want to make sure one of several radio buttons is selected, so you must access the length attribute of the whole radio group This is available by establishing a direct reference to the radio group

name on the form (document.formname.radiogroupname),

which coincidentally is the same as each radio button‘s name

Trang 8

switch(currElement.type) { case "select-one":

} else { return false;

}

13 If the form validated as true, the application will generate an alert

message: “The form is complete!” If it is false, it will generate an alert message saying “The selected field was not completed.”, and then set

focus to the element that is not valid Because the ElementLoop breaks when a problem occurs, currElement will be the violating element

Trang 9

Terminal: Routing and Setup

14 Now you can test the exercise The submitform variable will be false each

time, because the validation utility functions have not yet been defined Just make sure that there are no errors, and continue on to the next exercise The result should look something like Figure 7

TIP: A form button called shortcut and its corresponding function have been

added to the exercise files, so you can instantly fill in the form when shortcut

is clicked to save some keystrokes

Figure 7 The result of this exercise

Trang 10

string The default option, [Select], has an empty string for its value,

and would therefore be considered invalid if it were submitted with the form

 For the radio group, none of the radio buttons are checked by default, but one radio button must be checked by the user to be considered a valid submission

 The default value for the text and textarea objects is an empty string, but these elements must contain some character data in order to be considered valid entries

Step-by-Step Instructions

1 You will start by defining the text/textarea validation function, valText()

from the previous exercise Create an if block just after the declaration of the valid variable The expression for the if statement will be

(frmobj.value.length > 0), to test whether the length of the entry is greater

than zero; if so, the valid variable must be set to true with the statement

valid = true;

function valText(frmobj) { var valid = false;

if (frmobj.value.length > 0) { valid = true;

}

return valid;

Trang 11

Defining Validations

2 Next, define the select validation in the function valSelect() From the chapter you should remember that a select object has a selectedIndex

property, which will return the selected object‘s index position in the

options array Add an if block between the valid variable definition and the return valid; statement that has the condition

(frmobj[frmobj.selectedIndex].value.length > 0) This checks to make

sure that the selected Index has value

NOTE In Mozilla, the default value or the [Select] instruction-option

must have a value of ―‖ (an empty string) defined, or it will return

the selected option‘s label (i.e., [Select]) as the value

function valSelect(frmobj) { var valid = false;

if (frmobj[frmobj.selectedIndex].value.length > 0) { valid = true;

}

return valid;

}

3 Define the varRadio(frmobj) function, which will loop through the

objects in the radio group parameter that is passed in Create a for loop

block with the condition (ri = 0; ri < frmobj.length; ri++)

function valRadio(frmobj) { var valid = false;

for (ri = 0; ri < frmobj.length; ri++) {

if (frmobj[ri].checked) {

} }

return valid;

}

4 Within the loop block that you created in Step 3, create an if block with the

condition (frmobj[ri].checked) If the current radio object in the

radiogroup is checked, set the variable valid to true, using the statement

valid = true; On the next line, add a break; statement to ensure that the

code stops executing the loop once a checked radio object is found

Trang 12

function valRadio(frmobj) { var valid = false;

for (ri = 0; ri < frmobj.length; ri++) {

if (frmobj[ri].checked) { valid = true;

break;

} } return valid;

}

5 Now it is time to test the script Submit the form once with only one type

of form object selected (and the other types not selected) so that you can check each validation function If a required element is not selected or

filled in, it should receive focus after you click the OK button in the alert

message dialog box, as shown in Figure 8

Trang 13

Defining Validations

Figure 8 The alert message box in ValidateMe.html

Trang 14

Display Results

Objective

In this exercise, you will parse through and display the values of the form after

a successful submission by parsing through the query string for the page

1 Define a global variable at the bottom of the ValidateMe.js file called

submitmsg,and set it to reference an empty string

var submitmsg = "";

2 On the next line, define an if block with the condition:

(window.document.location.search.length > 0) This tests to see if there

are any parameters in the querystring, which means that the form has been submitted

if (window.document.location.search.length > 0) { }

3 Next, the application will build XHTML output into the submitmsg

variable, to be displayed on the page

NOTE There is already a place in the ValidateMe.html file that checks

submitmsg, and writes the contents if it has value:

Trang 15

Display Results

<! Display Submit Results >

<script language="JavaScript" type="text/javascript"> //submitmsg is declared in 'ValidateMe.js'

if (submitmsg) { document.write(submitmsg);

}

</script>

4 On the first line of the if statement from Step 3, create a new variable

called qs and assign it the value of window.document.location.search,

which is the query string with the question mark at the beginning On the

next line, create an array of name-value pairs called aQueryString Define

it by getting the name/value pairs from the query string by first removing

the question mark, then splitting the querystring at the ―&‖ character

TIP: So you can better see what you are working with, the query string will look

like this:

?_fname=111&_lname=112&city=113&state=114&_age=1020&_favsite= Yahoo&_comments=115&submit=Submit+Form

be split again into an array using the = character

5 Next you will start creating the submitmsg to display in

ValidateMe.html Start with the formatting, which you can copy from the

following code snippet:

Trang 16

submitmsg = "<fieldset class=\"fieldset\"><legend class=\"text\"><b>";

submitmsg += "Submission Results</b></legend><div align=\"center\">";

submitmsg += "<font class=\"text\" color=\"green\">";

// INSERT NAME / VALUES HERE

submitmsg += "</font></div></fieldset>";

6 Add a for loop where the comment // INSERT NAME / VALUES HERE

is located, with the condition (al = 0; al < aQueryString.length; al++)

This loop will iterate through the name-value pairs that were extracted into

the aQueryString array For the first statement in the loop, split up the

name and value of the current pair into another temporary array, using the

statement a = aQueryString[al].split(“=”);

for (al = 0; al < aQueryString.length; al++) { var a = aQueryString[al].split("=");

}

7 For the second statement in the loop, output the name and value of the

current index in the array in XHTML Remember, a[0] references the name and a[1] references the value:

for (al = 0; al < aQueryString.length; al++) { var a = aQueryString[al].split("=");

submitmsg += ("<b>" + a[0] + "</b> is equal to <b>" + a[1] + "</b><br/>");

}

8 Test the completed project by launching ValidateMe.html Once you have

completed the form and submitted it, all the values should be shown on the page, with the complete form resembling the one in Figure 9

Trang 17

Display Results

Figure 9 The final page after it has been completed successfully

Trang 19

Windows and Frames

Windows and

Frames

Objectives

 Learn how to spawn a new window using JavaScript

 Create content for windows spawned through JavaScript

 Learn how to launch functions in spawned windows

 See how to pass values to spawned windows

 Discover how to modify attributes

 Understand how to use modal dialog boxes in Internet Explorer 5+

 Discover how to create a frameset

 Understand the relationship between parent and child frames

 Learn how to use inline iframes

Trang 20

The Window Object

In order to make effective use of windows and frames, you need to have a good understanding of the window object The window object, which is at the top of the document object model hierarchy, is the outermost container of all document-related objects that you can script It encompasses all of the properties and behavior of the browser window itself, from the content area of the browser, to the scrollbars, toolbars, menu bar, and status bar (also known

as chrome), and even the dimensions of the window

NOTE Not all browsers provide you with full scripted control of the

chrome of the main browser window, but you may spawn a new window with exactly the chrome elements you desire

You can reference the properties and methods of the window object in several ways The most common way is to include the window object in the reference:

When the script references properties and methods of the current window, you may also omit the object reference altogether:

propertyName

methodName([params])

Ngày đăng: 09/08/2014, 06:22

TỪ KHÓA LIÊN QUAN

w