Presentation is loading. Please wait.

Presentation is loading. Please wait.

Advanced Web Development IT225

Similar presentations


Presentation on theme: "Advanced Web Development IT225"— Presentation transcript:

1 Advanced Web Development IT225
Spring Term 2016 Marymount University School of Business Administration Professor Suydam Week 7 JavaScript for Client-Side Computation and Data Validation (Chapter 6)

2 Week 7 Agenda Discuss MP2 Review Course Schedule Mini-Project 3
Chapter 6 JavaScript

3 Mini-Project2

4 Course Schedule

5 Mini-Project 3

6 Start MP3 (to be setup in class)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " <!-- buy2.html --> <html xmlns=" <head> <meta content="en-us" http-equiv="Content-Language" /> <title>Nature's Source - Canada's largest specialty vitamin store</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="css/default.css" /> </head> <body> <p><img src="images/naturelogo.gif" alt="Nature's Source" /></p> <h1>Final Project Proposal Site</h1> <table align="center" style="width: 800px"> <tr> <td> </td> </tr> </table> </body> </html> Copy/Paste your images, css, & common folders from MP2 to mp3 folder Copy/paste code at left and create/save an index.html file in mp3 folder Create a buttons folder in images folder Create a documents folder Install interactive buttons and link to various pages created during this class exercise Create link of frames page from MP3 (so you can easily view) Modify page to suit you and your project (e.g., logo, background, text, etc.)

7 Start MP3 (Continued) Create and insert buttons as shown below (your choice on button styles and text) Link from frames pages to MP3 index.html

8 Site Map (MS Visio) – actual Nature’s Source website (http://www

9 Chapter 6 Overview and Objectives
Discuss the importance of keeping web page content behavior separate from content structure and content presentation, both conceptually and physically Present an overview of JavaScript as a programming language, including a brief history, its limitations, and how we will use it Show how to write to a web page for user notification via JavaScript Distinguish between external and embedded JavaScript code Discuss the Document Object Model (DOM) and JavaScript access to it Discuss JavaScript data types and variables, functions (both built-in and programmer-defined), expressions, control statements, arrays, and built-in objects Discuss the importance of website security and how JavaScript can help to achieve it Introduce regular expressions and their use in JavaScript Update our BMI calculator form and our feedback form to incorporate validation of user input

10 Introduction: Structure vs. Presentation vs. Behavior
Earlier we saw a distinction between structure vs. presentation of a web page. Now we will make our web pages interactive using JavaScript. This introduces a new aspect of web pages: web page behavior. Although we can place JavaScript code directly on our HTML markup pages, the best practice is to separate behavior from presentation and content by keeping JavaScript code in a separate file. If we follow this best practice, we will achieve separation between these three things: the content of each HTML page and its structure the CSS file that determines page layout and presentation style the JavaScript code that determines page behavior

11 JavaScript What is JavaScript? (It's not Java!)
In the mid-1990s Netscape began development of a language called LiveScript for adding lively animations to web pages. Brendan Eich is credited with much of the early work. Sun Microsystems' Java programming language was fast gaining importance on the Internet due to these factors: its portability across different computing platforms its ability to provide users with interactivity on web pages via Java applets Netscape and Sun agreed to change the name LiveScript to JavaScript. Other than similarity in name, there is no obvious relationship between Java and JavaScript. Both languages share similar programming constructs, but those can be traced back to the popular C programming language. JavaScript is Interpreted, Not Compiled Programs in high-level languages need to be translated into machine language prior to execution. There are two types of translators: Compilers translate an entire program into an executable machine language version that can be executed many times, after this one-time translation. Interpreters translate a program one statement at a time to its machine language equivalent, just prior to the execution of that statement, and do this every time the program is run. Interpreted languages are simpler and more portable to different hardware and software platforms. The translation overhead of interpreted languages makes them generally less efficient than compiled languages.

12 JavaScript (Continued)
JavaScript and Client-Side Computing JavaScript can be used on both the client side (more common) and the server side (less common). Common server-side languages: PHP and Python (open-source) CGI programming using Perl (open-source) Java Server Pages™(JSP) technology (open-source) Active Server Pages (ASP) (proprietary) Typical Uses of JavaScript Computations based on user input Validation of data entered by the user, before that data is sent to the server for processing Dynamically adding HTML elements to a web page, or changing HTML elements already on a web page Changing the look and feel of a web page as the user’s mouse pointer interacts with the web page

13 Interactive Buttons Create a simple webpage containing interactive buttons <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " <!-- buy2.html --> <html xmlns=" <head> <meta content="en-us" http-equiv="Content-Language" /> <title>Nature's Source - Canada's largest specialty vitamin store</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="css/default.css" /> </head> <body> <p><img src="images/naturelogo.gif" alt="Nature's Source" /></p> <h1>JavaScript Test Pages site</h1> <table align="center" style="width: 800px"> <tr> <td> </td> </tr> </table> </body> </html> This is beginning of mp4 – we’ll get back to it after a couple weeks. Copy/Paste your images, css, & common folders from MP2 to mp4 folder Copy/paste code at left and create/save an index.html file in mp4 folder Create a buttons folder in images folder Install interactive buttons and link to various pages created during this class exercise Create link of frames page from MP4 (so you can easily view)

14 Create a Buttons Navigation Page
Link MP4 hypertext to new mp4 index.html page (so it opens in main frame of frames page) When setting Target Frame tap on area shown in green on image below:

15 Interactive Buttons Insert buttons in the center cell of the table; go to Insert>Interactive Button Change text for button name; format button using tabs in dialog; ensure you select radio button in image tab as shown by arrow. Save page -- Never trust Embedded file save dialog – always use “Change folder”

16 Simple Embedded JavaScript with Two Output Statements
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " <!-- buy2.html --> <html xmlns=" <head> <title>Nature's Source - Canada's largest specialty vitamin store</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <link rel="stylesheet" type="text/css" href="css/default.css" /> </head> <body> <p><img src="images/naturelogo.gif" alt="Nature's Source" /></p> <h3><script type="text/javascript"> document.write("Watch this space for our e-store.<br/>"); document.write("Coming soon ..."); </script></h3> </body> </html> JavaScript code embedded in HTML markup must appear as the content of a script element. The script element has this type attribute type="text/javascript“ indicating the language used in the script. The content of the script element is a sequence of JavaScript programming language statements to be executed when the browser reaches the script element during its processing of the page (two such statements in this case). Each JavaScript statement is terminated by a semicolon (;). In a JavaScript script, document refers to the HTML document containing the script. write() is a method (or function) “belonging to” document that can be used to write text information into the document for display. That information is the string (text enclosed in quotes) within the parentheses of write(). In JavaScript you will see and use many statements that “look like” this and have the generic form object.method(stuff). Note the parallels between a script element containing JavaScript code and a style element containing CSS.

17 buy3. html with Script Element accessing the JavaScript Code from buy3
buy3.html with Script Element accessing the JavaScript Code from buy3.js Replace instructions between <body></body> and resave buy2 as buy3 <!-- buy3.html --> ... <body> <p><img src="images/naturelogo.gif" alt="Nature's Source" /></p> <h3><script type="text/javascript" src=“js/buy3.js"> </script></h3> </body> Create a buy3.js document in the js folder – load to website and view in browser //buy3.js document.write("Watch this space for our e-store.<br/>"); document.write("Coming soon ...");

18 buy4. html with Script Element accessing the JavaScript Code from buy4
buy4.html with Script Element accessing the JavaScript Code from buy4.js Replace instructions between <body></body> and resave buy4 as buy4 <!– buy4.html --> ... <body> <p><img src="images/naturelogo.gif" alt="Nature's Source" /></p> <h3><script type="text/javascript" src=“js/buy4.js"> </script></h3> </body> Create a buy4.js document in the js folder – load to website and view in browser //buy4.js alert("Watch this space for our e-store.\n" + "Coming soon ...");

19 List of JavaScript Special Characters and Operators
Logical Operators in JavaScript Comparison Operators in JavaScript

20 The Document Object Model
The Document Object Model (DOM) is a W3C-defined standard Application Programming Interface (API) that programming languages like JavaScript can use to gain access to, and modify, parts of a web page. The DOM views every web page (document) as a hierarchical structure (model) of its elements (objects), determined by the nesting of those elements. The html element object is at the top, the head and body element objects are at the next level, and so on. When we use document.write() in a JavaScript script, we are using the write() method of the document property of the window object in the DOM for our web page.

21 Client-side Programming
function will be programming later in course. Usually data from a form is sent to the server for processing, but here we are dealing with client-side programming only, so we will not be sending our form data to a server in this chapter. All of our form data processing will be done on the client side using JavaScript. That is why the action attribute of the form tag still has an empty string as its value. (Scobey 186)

22 JavaScript <script></script> tags
Copy/Paste bmi and form pages created for mp2 into mp4 folder Add following script tags into the bmi page within the <head></head> tags <script type="text/javascript" src="js/bmi.js"></script>

23 JavaScript Function processBMIform()
Copy/paste the following function into a script page name bmi.js and save in the js folder function processBMIform() { var bmiFormObj = document.getElementById("bmiForm"); if (validateInput(bmiFormObj)) var bmi = calculateBMI(bmiFormObj); if (bmiFormObj.details.checked) displayDetailed(bmiFormObj, bmi); else alert("Your BMI: " + precision(bmi)); }

24 JavaScript Validation Function
Add following validation function after the previously pasted functions function validateInput(bmiFormObj) { var hUnit = bmiFormObj.heightUnit.options[bmiFormObj.heightUnit.selectedIndex].text; var wUnit = bmiFormObj.weightUnit.options[bmiFormObj.weightUnit.selectedIndex].text; var height = bmiFormObj.height.value; var weight = bmiFormObj.weight.value; var = bmiFormObj. .value; var heightOK, weightOK, OK; if (hUnit == "inches") heightOK = validateInches(height); else heightOK = validateCentimetres(height); if (wUnit == "pounds") weightOK = validatePounds(weight); weightOK = validateKilograms(weight); if (bmiFormObj.wantMail.checked) OK = validate ( ); alert("Warning: The feature is currently not supported.") } OK = true; return heightOK && weightOK && OK;

25 More Validating Functions
Add following validation functions after the previously pasted functions Height Weight function validateInches(height) { if (isNaN(height)) alert("Error: Please input a number for height.") return false; } if (height < 0 || height > 100) alert("Error: Height must be in the range inches.") return true; function validatePounds(weight) { if (isNaN(weight)) alert("Error: Please input a number for weight.") return false; } if (weight < 0 || weight > 1000) alert("Error: Weight must be in the range pounds.") return true; function validateCentimetres(height) { if (isNaN(height)) alert("Error: Please input a number for height.") return false; } if (height < 0 || height > 300) alert("Error: Height must be in the range centimeters.") return true; function validateKilograms(weight) { if (isNaN(weight)) alert("Error: Please input a number for weight.") return false; } if (weight <= 0 || weight > 500) alert("Error: Weight must be in the range kilograms.") return true;

26 E-mail Validating Function Using a Simple Regular Expression
Add following validation function after the previously pasted functions function validate (address) { var p = if (p == 0) return true; else alert("Error: Invalid address."); return false; } Note: Regular expressions will be examined in more detail later. This one simply says, “Look for at least one character followed followed by at least one more character.” So … not a very “robust” check for a valid !

27 JavaScript Code Illustrating Numeric Calculations
Add following calculation functions after the previously pasted validation functions function calculateBMI(bmiFormObj) { var hUnit = bmiFormObj.heightUnit.options[bmiFormObj.heightUnit.selectedIndex].text; var wUnit = bmiFormObj.weightUnit.options[bmiFormObj.weightUnit.selectedIndex].text; var height = bmiFormObj.height.value; var weight = bmiFormObj.weight.value; if (hUnit == "inches") height = inchesToCentimetres(height); if (wUnit == "pounds") weight = poundsToKilograms(weight); height /= 100; //Convert height from centimeters to meters var bmi = weight/(height*height); //kilograms/(meters*meters) return bmi; } function inchesToCentimetres(height) { var CENTIMETRES_PER_INCH = 2.54; return height * CENTIMETRES_PER_INCH; } function poundsToKilograms(weight) var POUNDS_PER_KILOGRAM = 2.2; return weight / POUNDS_PER_KILOGRAM;

28 JavaScript Code Illustrating the Building of a String Object for Output
Add following display functions after the previously pasted functions function displayDetailed(bmiFormObj, bmi) { var hUnit = bmiFormObj.heightUnit.options[bmiFormObj.heightUnit.selectedIndex].text; var wUnit = bmiFormObj.weightUnit.options[bmiFormObj.weightUnit.selectedIndex].text; var height = bmiFormObj.height.value; var weight = bmiFormObj.weight.value; var text = "BMI Report\n" + "Your weight: " + weight + " " + wUnit + "\n" + "Your height: " + height + " " + hUnit + "\n" + "Your BMI: " + precision(bmi) + "\n"; if (bmi < 18.5) text += "Your BMI suggests that you are underweight.\n"; else if (bmi < 25) text += "Your BMI suggests that you have a reasonable weight.\n"; else if (bmi < 29) text += "Your BMI suggests that you are overweight.\n"; else text += "Your BMI suggests that you may be obese.\n"; alert(text); }

29 Supplementary JavaScript Code Illustrating the Building of a String Object for Output
Add following math precision function after the previously pasted functions function precision(num) { var intPortion = Math.floor(num); var decimalPortion = Math.round(num*10)%10; var text = intPortion + "." + decimalPortion; return text; }

30 JavaScript Math objects
Constants Methods

31 A Browser Display of the Result of a Typical BMI Calculation

32 Revise feedback.html Add following script tags into the feedback page in mp4 folder within the <head></head> tags <script type="text/javascript" src="js/feedback.js"> </script> Replace the original beginning form tag <form id="contact" action=""> with: <form id="contactForm" action="" onsubmit="validateContactForm()">

33 Validation Functions for feedback.js
function validateContactForm() { var contactFormObj = document.getElementById("contactForm"); var firstName = contactFormObj.firstName.value; var lastName = contactFormObj.lastName.value; var phone = contactFormObj.phone.value; var = contactFormObj. .value; var everythingOK = true; if (!validateName(firstName)) alert("Error: Invalid first name."); everythingOK = false; } if (!validateName(lastName)) alert("Error: Invalid last name."); if (!validatePhone(phone)) alert("Error: Invalid phone number."); if (!validate ( )) alert("Error: Invalid address."); if (everythingOK) alert("All the information looks good.\nThank you!"); return true; else return false; function validateName(name) { var p = name.search(/^[-'\w\s]+$/); if (p == 0) return true; else return false; } function validatePhone(phone) var p1 = phone.search(/^\d{3}[-\s]{0,1}\d{3}[-\s]{0,1}\d{4}$/); var p2 = phone.search(/^\d{3}[-\s]{0,1}\d{4}$/); if (p1 == 0 || p2 == 0) function validate (address) var p =

34 A Browser Display of Two Different Feedback Form Errors Generated from feedback.html

35 Client-side Programming
function will be programmed later in course. . Since we are only dealing with client-side computing using JavaScript, we have not implemented the facility. All that happens is a message using the alert() method will be displayed to the user. Allowing JavaScript programs to send s from a client’s computer would be a major breach of security since malicious JavaScript code could exploit the ability to send spam from client computers. We will implement the facility when we study server-side computing using PHP. (Scobey )

36 Special Characters in JavaScript Regular Expressions
Characters Denoting Positions in JavaScript Regular Expressions Characters that Can Be Used in JavaScript Regular Expressions

37 Special Characters in JavaScript Regular Expressions (Continued)
Character Classes that Can Be Used in JavaScript Regular Expressions Modifiers that Can Be Placed after a Pattern within a JavaScript Regular Expression to Indicate the Permissible Amount of Repetition of that Pattern

38 Understanding JavaScript Programming
Once you have BMI Calculator and Feedback form working go back and read Chapter 6, then do Study Guide 3, to make sure you understand all the concepts.

39 MP4 Starter Site


Download ppt "Advanced Web Development IT225"

Similar presentations


Ads by Google