1 / 63

JavaScript

JavaScript. JavaScript and HTML Text Chapter 4. Client-side JavaScript. Defines a collection of objects, methods and properties that allow scripts to interact with XHTML. This chapter covers DOM, although an understanding of DOM is not necessary to use client-side JavaScript.

lei
Download Presentation

JavaScript

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JavaScript JavaScript and HTML Text Chapter 4

  2. Client-side JavaScript • Defines a collection of objects, methods and properties that allow scripts to interact with XHTML. • This chapter covers DOM, although an understanding of DOM is not necessary to use client-side JavaScript. • It covers techniques for accessing document elements, and the basics of events and event-handling.

  3. DOM • The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents.[1] Objects in the DOM tree may be addressed and manipulated by using methods on the objects. The public interface of a DOM is specified in its application programming interface (API). The history of the Document Object Model is intertwined with the history of the "browser wars" of the late 1990s between Netscape Navigator and Microsoft Internet Explorer, as well as with that of JavaScript and JScript, the first scripting languages to be widely implemented in the layout engines of web browsers.

  4. The execution environment • A browser displays an XHTML document in a window on the computer screen. This is the JavaScript Window object. • All variables in your script are properties of some object. The Window’s properties are visible to all scripts in the displayed document, (this includes global variables). • There can be multiple Window objects. • The Document object is the displayed HTML document. It is a property (the document property) of a Window object. • The Document object has a Forms array. Each Forms array element has an elements array as a property. • The Document object also has a property arrays for anchors, links, images and applets.

  5. Hierarchy

  6. DOM: Document Object Model • Under development since mid-90s. • Currently DOM 3 is the latest version • DOM1 focused on the XHTML and XML document model. • DOM 2 includes document traversal and an event model.

  7. Values indicate the level of support in the most recent version of the layout engine, or (if a version number is given) in the specified version.

  8. DOM compliance by layout engines

  9. The document object <html > <head> <title> onLoad event handler </title> <script type = "text/javascript"> // The onload event handler function load_greeting () { alert("You are visiting the home page of \n" + "Pete's Pickled Peppers \n" + "WELCOME!!!"); } </script> </head> <body onload="load_greeting();"> Some text <p /> </body> </html>

  10. The previous html rendered

  11. The document object document body head script title Some text function

  12. DOM support in JavaScript • Elements of XHTML are objects in JavaScript, their attributes are object properties. Example, <input type=“text” name=“address”> • type and name are properties of the input object

  13. Accessing objects and properties • Addresses are needed to access objects and properties of the document from within a script. • The address is referred to as the object’s DOM address.

  14. Text example <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head><title> address example </title> </head> <form name ="myform" action=""> <input type="button" name="turniton"> </form> </body> </html>

  15. Address of the button is…? • Using the DOM address, the button is document.forms[0].elements[0] • Using element names, the address of the button is document.myForm.turniton • A validation issue: the XHTML 1.1 standard does not allow the use of the name attribute for a form, though the browser has no trouble with it. • You can also use a JavaScript method, getElementById(“…”) as in document. getElementById(“turniton”) • Any expression that evaluates to string can serve as the parameter to getElementById

  16. Names and ids • Names are needed for form-processing and ids are handy for DOM addressing so often both are used. • Buttons in a group of radiobuttons always have the same name. Buttons in a group of checkboxes may have the same name. In such cases, the names cannot be used in the DOM address. They may have an id though. • Implicit arrays are associated with button groups, and these provide an alternative to using names or ids for these addresses. (See course ppt example).

  17. Table 5.2 excerpt: Text shows event attributes and their tags

  18. How to register the event handler with DOM 0 event model • Assign the event handler script to an event tag attribute, eg., <input type =“button” name=“whocares” onclick=“alert(‘you clicked me’);”/> • If the handler is more than one statement, use a function, as in, <input type =“button” name=“whocares” onclick=“myButtonHandler();”/>

  19. Body elements • load and unload are the two most common body-element events. • See text example load greeting in previous slide

  20. Buttons • Buttons are a good way to get input from a browser. click is the most common button event • Example from previous slide shows how to register an event to handle button-click: <input type =“button” name=“whocares” id=“somebutton” onclick=“myButtonHandler();”/>

  21. Buttons • Another way to do it would be to assign the handler to the associated event property on the button: document.getElementById(“somebutton”).onclick= myButtonHandler;

  22. Rb example: form in body <form id = "myForm" action = ""> <p> <input type = "radio" name = "planeButton" onclick = "planeChoice(152)" /> Model 152 <br /> <input type = "radio" name = "planeButton" onclick = "planeChoice(172)" /> Model 172 (Skyhawk) <br /> <input type = "radio" name = "planeButton" onclick = "planeChoice(182)" /> Model 182 (Skylane) <br /> <input type = "radio" name = "planeButton" onclick = "planeChoice(210)" /> Model 210 (Centurian) </p> </form>

  23. Slightly modified Radiobutton click event handler function planeChoice (plane) { var plane; var s; switch (plane) { case 152: s="A small two-place-airplane for flight training"; break; case 172: s="The smaller of two four-place airplanes"; break; case 182: s="The larger of two four-place airplanes"; break; case 210: s="A six-place high-performance airplane"; break; default: s="Error in JavaScript function planeChoice"; } alert(s);}

  24. The form

  25. Alert from rb click

  26. Different version of this rb example <body> <h4> Cessna single-engine airplane descriptions </h4> <form id = "myForm" action = "handler"> <p> <input type = "radio" name = "planeButton" value = "152" /> Model 152 <br /> <input type = "radio" name = "planeButton" value = "172" /> Model 172 (Skyhawk) <br /> <input type = "radio" name = "planeButton" value = "182" /> Model 182 (Skylane) <br /> <input type = "radio" name = "planeButton" value = "210" /> Model 210 (Centurian) </p> </form> <script type = "text/javascript"> var dom = document.getElementById("myForm"); dom.elements[0].onclick = planeChoice; dom.elements[1].onclick = planeChoice; dom.elements[2].onclick = planeChoice; dom.elements[3].onclick = planeChoice; </script>

  27. Different version of the same from text function planeChoice (plane) { var dom = document.getElementById("myForm"); for (var index = 0; index < dom.planeButton.length; index++) { if (dom.planeButton[index].checked) { plane = dom.planeButton[index].value; break; } } switch (plane) { case "152": alert("A small two-place airplane for flight training"); break; case "172": alert("The smaller of two four-place airplanes"); break; case "182": alert("The larger of two four-place airplanes"); break; case "210": alert("A six-place high-performance airplane"); break; default:: alert("Error in JavaScript function planeChoice"); break; } }

  28. Text box events • Textbox creates four events: blur, focus, change, select.

  29. An example from the text • Text example (pg 207 nochange.html and nochange.js) • I saved this in • …\Higgindm\source\chapt5\coffee.html and coffee.js

  30. The Compute cost function function computeCost() { var french = document.getElementById("french").value; var hazlenut = document.getElementById("hazlenut").value; var columbian = document.getElementById("columbian").value; // Compute the cost document.getElementById("cost").value = totalCost = french * 3.49 + hazlenut * 3.95 + columbian * 4.59; } //* end of computeCost

  31. A piece of the table to create the form <tr> <th> Product Name </th> <th> Price </th> <th> Quantity </th> </tr> <!-- Now, the table data entries --> <tr> <th> French Vanilla (1 lb.) </th> <td> $3.49 </td> <td> <input type = "text" id = "french" size ="2" /> </td> </tr> <tr>

  32. computation of the total cost <p> <input type = "button" value = "Total Cost" onclick = "computeCost();" /> <input type = "text" size = "5" id = "cost" onfocus = "this.blur();" /> </p>

  33. Ordering coffee: user can’t alter any cost or price textbox

  34. Validating form input • Format, completeness (including datatypes, etc) is commonly done in JavaScript, shifting this work off the server. Besides the fact that the client usually has a lighter load, doing this data entry checking on the client saves network traffic. • An alert indicating the error, putting the field in focus, and selecting the contents would be appropriate actions. The focus() method and select() methods on the DOM element would effect the latter two actions.

  35. IE6 vs Moz7 • In IE6 focus and select only work if the handler is registered by assigning an event property. In Moz7 select works ok but focus does not.

  36. Return value of data checking handler • A handler checking form data should return false to keep the (bad) form data from being sent on to the server.Return true if the data is ok. • The text provides an example: the user enters a password, then enters it again. We need to check that the pw was entered into the first field (it is not the empty string) and that the contents of the first pw field match the second pw field. • If all is well the checker returns true. Otherwise it returns to the first pw field. • The checker is called on submit, or when the second textbox loses focus, the onblur event.

  37. Entering two different pws in mozilla

  38. After clicking ok in the alert in IE: note focus

  39. Function to check pws function chkPasswords() { var init = document.getElementById("initial"); var sec = document.getElementById("second"); if (init.value == "") { alert("You did not enter a password \n" + "Please enter one now"); init.focus(); return false; } if (init.value != sec.value) { alert("The two passwords you entered are not the same \n" + "Please re-enter both now"); init.focus(); init.select(); return false; } else return true;}

  40. Body & form <body><h3> Password Input </h3> <form action = ""> <p> Your password <input type = "password" id = "initial" size = "10" /> <br /><br /> Verify password <input type = "password" id = "second" size = "10" /> <br /><br /> <input type = "reset" name = "reset" /> <input type = "submit" name = "submit" /> </p> </form> <script type = "text/javascript"> <!-- // Set submit button onsubmit property to the event handler document.forms[0].onsubmit = chkPasswords; // --> </script></body>

  41. Validator example in text • Check a name and phone number for format errors.

  42. Input validation: check name

  43. Checking input: phone number

  44. This input was accepted…. Is it ok?

  45. Check name function chkName() { var myName = document.getElementById("custName"); // Test the format of the input name // Allow the spaces after the commas to be optional // Allow the period after the initial to be optional var pos = myName.value.search(/\w+, ?\w+, ?\w.?/); if (pos != 0) { alert("The name you entered (" + myName.value + ") is not in the correct form. \n" + "The correct form is: " + "last-name, first-name, middle-initial \n" + "Please go back and fix your name"); myName.focus(); myName.select(); return false; } else return true; }

  46. Check number function chkPhone() { var myPhone = document.getElementById("phone"); // Test the format of the input phone number var pos = myPhone.value.search(/^\d{3}-\d{3}-\d{4}$/); if (pos != 0) { alert("The phone number you entered (" + myPhone.value + ") is not in the correct form. \n" + "The correct form is: ddd-ddd-dddd \n" + "Please go back and fix your phone number"); myPhone.focus(); myPhone.select(); return false; } else return true; }

  47. Form and script <form action = ""> <p> <input type = "text" id = "custName" /> Name (last name, first name, middle initial) <br /><br /> <input type = "text" id = "phone" /> Phone number (ddd-ddd-dddd) <br /><br /> <input type = "reset" id = "reset" /> <input type = "submit" id = "submit" /> </p> </form> <script type = "text/javascript"> <!-- // Set form element object properties to their // corresponding event handler functions document.getElementById("custName").onchange = chkName; document.getElementById("phone").onchange = chkPhone; // --> </script>

  48. Validator2 from text • Uses the DOM2 model. • Documents can mix the Dom0 and DOM2 models. • But DOM2 is not a superset of DOM0 and doesn’t support its model.

  49. the DOM2 model

  50. DOM2 event-handling • much more complicated than DOM0: There are 3 phases: capture, target node execution, and bubbling • In capture, the event object propagates down from the root to the target node looking for an enabled event-handler. • When the event reaches the target node, any registered handler there are executed. • In bubbling, the event travels back to the root executing enabled event-handlers for this event.

More Related