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

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

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

Nội dung

ptg 13.6 Handling a Form Event 489 13.6.5 Forms and the onChange Event Handler 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. EXAMPLE 13.16 <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'); } 4 else{ confirm('Is '+ grade + ' correct?'); } 5 " /> 6 </form> </body> </html> From the Library of WoweBook.Com ptg 490 Chapter 13 • Handling Events EXPLANATION 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. From the Library of WoweBook.Com ptg 13.6 Handling a Form Event 491 13.6.6 Forms and the onSubmit Event Handler 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. EXAMPLE 13.17 <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 From the Library of WoweBook.Com ptg 492 Chapter 13 • Handling Events </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> EXPLANATION 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. EXAMPLE 13.17 (CONTINUED) From the Library of WoweBook.Com ptg 13.6 Handling a Form Event 493 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. EXPLANATION ( CONTINUED) From the Library of WoweBook.Com ptg 494 Chapter 13 • Handling Events EXAMPLE 13.18 <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> From the Library of WoweBook.Com ptg 13.6 Handling a Form Event 495 EXPLANATION 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. From the Library of WoweBook.Com ptg 496 Chapter 13 • Handling Events 13.6.7 HTML Event Handlers and JavaScript Event Methods 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. EXAMPLE 13.19 <html> <head><title>Event Handling</title> <script type="text/javascript"> var tries=0; 1 function randomize(){ // Random number is set when the document has loaded var now=new Date(); num=(now.getSeconds())%10; //modulus-remainder after division num++; } 2 function guessit(form){ // Function is called each time the user clicks the button if (form.tfield.value == num){ alert("Correct!!"); 3 form.tfield.focus(); n=0; randomize(); } From the Library of WoweBook.Com ptg 13.6 Handling a Form Event 497 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" 8 value="Check my guess" 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/. EXPLANATION 1 A function called randomize() is defined. It will create a random number by divid- ing the number of seconds by 10 and returning 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 EXAMPLE 13.19 (CONTINUED) From the Library of WoweBook.Com ptg 498 Chapter 13 • Handling Events 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. EXAMPLE 13.20 <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); } EXPLANATION ( CONTINUED) From the Library of WoweBook.Com [...]... the image loads (right) 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 document; 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), . <h3>Form data</h3>"); newWin.document.write("<b>Your name is:</b> " + document["form1"].namestring.value); newWin.document.write("<br /><b>Your. 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. newWin.document.write("<br /><b>Your address is: </b></body>" +document["form1"].address.value); newWin.document.close(); } </script> Continues From the Library of WoweBook.Com ptg 492

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

TỪ KHÓA LIÊN QUAN