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

Học JavaScript qua ví dụ part 54 doc

11 193 0
Tài liệu đã được kiểm tra trùng lặp

Đ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 11
Dung lượng 1,09 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The onChange event handler is triggered after the user modifies the value or contents of an HTML input, select, or text area element in a form, and then releases the mouse.. If you reca

Trang 1

The onChange event handler is triggered after the user modifies the value or contents of

an HTML input, select, or text area element in a form, and then releases the mouse This

is another event handler that can be useful in checking or validating user input

Figure 13.18 Look at the status bar You might have to enable the View Status Bar

feature for your browser.

E X A M P L E 1 3 1 6

<html>

<head><title>onChange Event Handler</title></head>

<body>

1 <form>

Please enter your grade:

2 <input type="text" onChange="

grade=parseInt(this.value); //Convert to integer

3 if(grade < 0 || grade > 100){

alert('Please enter a grade between 0 and 100');

}

confirm('Is '+ grade + ' correct?');

}

5 " />

6 </form>

</body>

</html>

Trang 2

E X P L A N A T I O N

1 The HTML form starts here

2 The input type is a text field The onChange event is triggered when something

changes in the text field box, such as a user entering input Instead of assigning a

function to the handle the event, the JavaScript statements are enclosed in double

quotes and will be parsed and executed when the event is triggered It might be

less error prone to write a function than to try to keep this whole section of code

enclosed in quotes

3 If the input assigned to grade is less than 0 or greater than 100, it is out of the legal

range, causing an alert box to appear

4 If the input was within the limits, then the else block is executed A confirm box

will appear to verify that this is what the user meant to type

5 This quote marks the end of the JavaScript statements, and the > marks the end

of the input type tag

6 The HTML form ends here The actions of the handler are shown in Figures 13.19

through 13.21

Figure 13.19 The user enters no value at all: There is no change.

Figure 13.20 The user enters a value A change has taken place within the

textbox The onChange handler is invoked.

Figure 13.21 The user enters a value The onChange handler is invoked The value

entered was out of range, causing the alert box to appear.

Trang 3

When you submit an online order for a purchase you made at a Web site like Amazon

or iTunes, once you have submitted the order, you can’t back out It’s too late You have

your e-mail confirmation before you can blink an eye, your new tune or movie ready

to play, and your payment has already been processed You pressed the submit button,

maybe with a different label, like “Order now,” but pressing that button triggered an

event that caused your order to be processed

The onSubmit event handler was discussed in detail in Chapter 11, but it is included

again in this chapter because it is such an important form event You will see this event

again in Chapter 17 If you recall, the onSubmit event is an attribute of the HTML <form>

tag and is triggered when the user presses the submit button after filling out a form This

event allows the programmer to validate the form before sending it off to the server If the

return value from the event handler is true, the form will be submitted; if false it won’t be

submitted The following examples demonstrate two different programs using an onSubmit

event handler Example 13.17 creates two text fields for the user’s name and address The

onSubmit event handler is triggered when the user clicks the submit button, causing a

function to be called that will produce a little popup window with the user’s input data By

allowing the user to view the data entered, the submission can be delayed for further

vali-dation, and so on Example 13.18 is a snippet of code that could be used after a shopping

cart has been filled and the user is ready to go to the checkout page When the user clicks

the submit button labeled “Go to Checkout” a function will be called It returns true if the

user has checked a checkbox and false if he or she hasn’t By checking the small checkbox,

the user is confirming that he or she is ready to submit the form data Then a server side

program will perform further validations and calculations, send e-mail, open a database,

and so on Both of the examples show the value of having an onSubmit handler to catch

the form before it is submitted to allow the user to change a field, go back to another page,

confirm that he or she has finished and is ready to order, and so on

E X A M P L E 1 3 1 7

<html>

<head><title>The onSubmit Event Handler</title>

<script type="text/javascript">

1 function popUp(){

2 newWin=window.open('','NewWin','toolbar=no,

status=no,width=500,height=200');

3 newWin.document.write("<body bgcolor='yellow'>

<h3>Form data</h3>");

newWin.document.write("<b>Your name is:</b> " + document["form1"].namestring.value);

newWin.document.write("<br /><b>Your address is:

</b></body>" +document["form1"].address.value);

newWin.document.close();

}

</script>

Continues

Trang 4

</head>

<body bgcolor="yellow">

4 <form name="form1" onSubmit="return popUp();">

<p>

<table>

<tr>

<td>

<b>Type your name:</b>

</td>

<td>

5 <input type="text"

name="namestring"

size="50">

</td>

</tr>

<tr>

<td>

<b>Type in your address:</b>

</td>

<td>

6 <input type="text"

name="address"

size="80">

</td>

</tr>

</table>

<p>

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

<input type="reset" value="Clear" />

</form>

</body>

</html>

E X P L A N A T I O N

1 A function called popUp() is defined It will cause a popup window to appear with

data that was entered into a form (Your browser might not allow popup windows

unless you change a setting.)

2 This is where the new window object is created and assigned properties (In this

example, the line is broken to make it fit on the page, but if you do this in a script,

make sure there are no spaces between any of the window options.)

3 The write() method will send its output to the new window.

E X A M P L E 1 3 1 7 (C O N T I N U E D)

Trang 5

4 The HTML form starts here When the submit button is clicked, the onSubmit

event handler will be triggered and call the popUp() function, causing a new

pop-up window to appear containing the information that the user typed into the

form At this point the program could ask the user if the data is valid and continue

to process the information by sending it to a server Because the action attribute

for the HTML form hasn’t been defined, nothing will happen

5 The input types for the form are defined here as two textboxes, one for the user’s

name and one for the address

6 The submit button is created here When the user submits the form, the onSubmit

handler on line 4 will be triggered The action is shown in Figures 13.22 and 13.23

Figure 13.22 The fillout form.

Figure 13.23 Popup window with form data after submit.

E X P L A N A T I O N (C O N T I N U E D)

Trang 6

E X A M P L E 1 3 1 8

<html>

<head><title>Check it Out!</title>

<script type="text/javascript">

// Script modified from original found at // http://JavaScript.internet.com

1 function okForm(form){

if (form.accept.checked == true){

return true;}

else{

alert("Please check the box!");

form.accept.focus();

return false;}

}

</script>

</head>

<body bgcolor="#CCCCFF">

<font face="arial,helvetica" size=2>

2 <form action="http://localhost/phpexamples/processform.php"

method="post"

3 onSubmit="return okForm(this)">

<b>Your name:</b><br />

4 <input type="text" name="yourname">

<p>

<b>What will you purchase today?</b><br />

</p>

<input type="radio" name="choice"

value="burger">Burger, fries and coke

<br />

<input type="radio" name="choice"

value="veggie">Veggies and Vitamin water

<p>

<b>Thank you for your order.

Check the box and then "Go to Checkout".</b></p>

5 <input type="checkbox"

name="accept"

value="0" />

6 <input type="submit"

value="Go to checkout" />

</p>

7 <input type="button"

value="Go back to Home Page"

onClick="window.location.replace('http://localhost';)">

</font>

</form>

</body>

</html>

Trang 7

E X P L A N A T I O N

1 A function called okForm() is defined The function is called by the onSubmit event

handler Its purpose is to ensure that a checkbox has been checked before allowing

the user to submit the form If it has, the return value is true, and the form will be

submitted If not, the user will be reminded to check the box, false will be returned,

and the form will not be submitted See Figure 13.24 Once the checkbox has been

checked, and the submit button labeled “Go to Checkout” clicked, the form will be

submitted to the URL address assigned to the form’s action attribute; in this case a

PHP script called “processform.php” (see Figure 13.25)

2 The action attribute is the URL of the server where the form data will be sent for

processing, once it has been submitted

3 The onSubmit event handler is triggered when the user clicks the submit button

for this form

4 This is the part of the form where the user enters data to be sent to the server-side

program for processing

5 This is the checkbox that must be clicked before the user can submit the form

The okForm() checks to see if this box was checked before allowing the form to

be submitted

6 When this submit button, labeled “Go to Checkout” is pressed, the onSubmit

han-dler on line 3 is triggered

7 When the user presses this button, the onClick handler will be fired up, and cause

the page to be redirected to the shopping cart page for the site

Figure 13.24 The user cannot go to checkout (i.e., submit the form) until he or she

clicks the little box at the left.

Trang 8

You’ll find that many JavaScript programs use a combination of event handlers and event

methods, especially when working with forms Example 13.19 uses event handlers and

event methods It creates a random number between 1 and 10, and asks the user to guess

what the number is As soon as the document is loaded, the onLoad event handler is

trig-gered, and when the user clicks the button, the onClick handler is fired up The focus()

method is used to put focus in the textbox where the user will enter his or her guess

Figure 13.25 After the user checks out, the PHP script processes the input data

from the form.

E X A M P L E 1 3 1 9

<html>

<head><title>Event Handling</title>

<script type="text/javascript">

var tries=0;

// Random number is set when the document has loaded

var now=new Date();

num=(now.getSeconds())%10;

//modulus-remainder after division

num++;

}

// Function is called each time the user clicks the button

if (form.tfield.value == num){

alert("Correct!!");

n=0;

randomize();

}

Trang 9

else{

tries++;

4 alert(tries + " Wrong Try again.");

form.tfield.value=""; // Clear the textbox

form.tfield.focus(); // Put the cursor in the textbox

} } // End hiding from old browsers >

</script>

</head>

<body bgcolor="lightgreen"

5 onLoad="randomize()"> <! Call function when page is loaded >

<center>

<b>Pick a number between 1 and 10</b>

<form name="myform">

6 <input type="textbox" size=4

name="tfield" />

<p>

7 <input type="button"

name="button1"

onClick="guessit(this.form)" /> </p>

</form>

</body>

</html>

This script was modified from one written by Andree Growney originally available at

http://www.htmlgoodies.com/primers/jsp/

E X P L A N A T I O N

1 A function called randomize() is defined It will create a random number by

divid-ing the number of seconds by 10 and returndivid-ing the remainder (modulus); for

ex-ample, 59/10 would return the number 9 Then, by adding 1 to that, we get 10

2 The function called guessit will take one argument, a reference to the form Its

purpose is to see if the number entered by the user, form.tfield.value, matches the

value of the random number calculated in the randomize() function

3 The focus() method puts the cursor in the text field

4 If the user guessed wrong, the alert dialog box appears and tells him or her so, the

text field is cleared, and focus is put there

5 Once the document has loaded, the onLoad event handler is triggered, causing

the function randomize() to be called This sets the initial random number for

the program

Continues

E X A M P L E 1 3 1 9 (C O N T I N U E D)

Trang 10

13.6.8 The onError Event

The error event fires when a JavaScript error has occurred (window) or when an image

cannot be found (image elements)

6 The form’s input type is a textbox This is where the user will enter his or her guess

7 This input type is a button

8 When the user clicks this button, the onClick event handler is triggered, causing

the guessit() function to be called with this form as an argument The display is

shown in Figures 13.26 and 13.27

Figure 13.26 The user makes a guess (left), but is told he or she guessed wrong (right).

Figure 13.27 Focus returns to the form field.

E X A M P L E 1 3 2 0

<html>

<head><title>Wake up call</title>

<script type="text/javascript">

function wakeupCall(){ // Function is defined here

timeout=setTimeout('alert("Time to get up!")',2000);

}

E X P L A N A T I O N (C O N T I N U E D)

Trang 11

13.7 The event Object

As we have seen throughout this text, events are happening all the time with JavaScript

Event objects are sent to an event handler with each event that occurs within a

docu-ment; for example, when the user clicks on the left mouse button, JavaScript registers

the event, what key was pressed, its coordinates (pixel positions of where it was pressed

on the screen), and so on To learn more about what happened so that you can track

problems, get pixel coordinates, find out what button was pushed or what key was

released, and so on, the event object provides specific information about the event This

topic can be very confusing because W3C, Mozilla/Firefox type browsers, and Microsoft

Internet Explorer differ in how events should be handled Like economists argue over

</script>

</head>

<body bgcolor="white">

<form>

<div align="center">

<p>

1 <image src="Image/java_steam.gif"

2 onError="alert('Image is having trouble loading!')">

</p>

<input type="button"

value="Wake me"

onClick="wakeupCall()" />

</div>

</form>

</body>

</html>

E X P L A N A T I O N

1 The <image> tag identifies the src of a gif image to be loaded from a subdirectory

called Image.

2 The onError event handler is triggered when an error occurs while loading the

image See Figure 13.28

Figure 13.28 The onError event handler was triggered because the image src was

wrong (left), and after the image loads (right).

E X A M P L E 1 3 2 0 (C O N T I N U E D)

Ngày đăng: 04/07/2014, 02:20

TỪ KHÓA LIÊN QUAN