• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Week 7
 

Week 7

on

  • 694 views

Week 7

Week 7

Statistics

Views

Total Views
694
Views on SlideShare
686
Embed Views
8

Actions

Likes
0
Downloads
8
Comments
0

1 Embed 8

http://www.deinega.com 8

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Week 7 Week 7 Presentation Transcript

    • Homework• Submit a brief essay on which do you prefer – client side scripting versus server side scripting and why?• Read JavaScript chapters 6 ,7, 8
    • Web Technology Stack Data – What does it know? Behavior – What does it do? Behavior – What does it do? Presentation – What does it look like? Structure – What does this logically mean? Richness of theExperience
    • Exercise #1
    • Design by fiat“I read about JavaScript and it’sreally cool. So let’s refactor thefuture value app. Do me a favor,make the background orange…I’ma huge Jeremy Lin fan.”
    • Chapter 2 How to code a PHP applicationMurachs PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 6
    • The first pageMurachs PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 7
    • The second pageMurachs PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 8
    • From index.php to future_value.html<!DOCTYPE html><html lang=”en”><head> <title>Future Value Calculator</title> <meta charset="UTF-8" /> <link rel="stylesheet" href="css/future_value.css" /></head><body> <divsection id="content"> <h1>Future Value Calculator</h1> <?php if (!empty($error_message)) { ?> <p class="error"><?php echo $error_message; ?></p> <?php } ?> <form action="display_results.php" method="post"> <divform id="data"> <p>Enter the values below and click "Calculate".</p> <label for=”investment”>Investment Amount:</label> <input type="text" name="investment" value=id"<?php echo $investment; ?> "/><br />
    • From index.php to future_value.html (continued) <label for=”interest_rate”>Yearly Interest Rate:</label> <input type="text" name="interest_rate" value=id="<?php echo $interest_rate; ?>"/><br /> <label for=”years”>Number of Years:</label> <input type="text" name="years" value=id="<?php echo $years; ?>"/><br /> <label for="future_value">Future Value:</label> <input type="text" name="future_value” id="future_value" disabled" /><br /> </divform> <div id="buttons"> <label>&nbsp;</label> <input type="submit" value="Calculate"/><br /> </div> </form> </divsection></body></html>
    • From main.css to css/future_value.cssbody { font-family: Arial, Helvetica, sans-serif; background: orange;}#content { width: 450px; margin: 0px auto; padding: 20px 20px; background: white; border: 2px solid navy;}h1 { color: navy;}label { width: 10em; padding-right: 1em; float: left;}
    • From main.css to css/future_value.css#data input { float: left; width: 15em; margin-bottom: .5em;}#buttons input { float: left; margin-bottom: .5em;}br { clear: left;}.error { color: red; font-weight: bold;}
    • What we have so far
    • The world’s most misunderstood programming language“JavaScript has so muchexpressive power that youcan get a lot done withoutknowing what your doing.” --Douglas Crockford
    • Introduction of JavaScript JavaScript is an interpreted programming or script language invented by Netscape programmer Brendan Eich JavaScript allows web developers to manipulate the DOM on the client-side
    • Scripting Languages and the First Browser War JavaScript JScript Sept 1995 Nov 1996 ProprietaryJScript is identical to JavaScript but…•Some JavaScript commands not supported in JScript•Some JScript commands not supported in JavaScript
    • European Computer Manufacturing Association Takes Over ECMAScript Jun 1997 StandardECMAScript is based on JavaScript, Jscript, andActionScript•ECMA-262 5th edition codifies de facto interpretations ofthe language specification that have become commonamong browsers
    • Chapter 2 How to code a JavaScript application*Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 19
    • *Updates for this class• XHMTL rules supersede by HTML5 and will be noted where appropriateMurach’s JavaScript, C4 © 2009, Mike Murach & Associates, Inc. Slide 20
    • Agenda• Basic JavaScript skills ⇒ How to include JavaScript• How to use objects• How to code control statements• How to create and use functions
    • How to load JavaScript from an external file <script type="text/javascript" src="sales_tax.js"></script> How to embed JavaScript in the head section <head> ... <script type="text/javascript"> var $ = function (id) { return document.getElementById(id); } </script> ... </head>Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 22
    • How to embed JavaScript in the body section <p>&copy; <script type="text/javascript"> var today = new Date(); document.writeln( today.getFullYear() ); </script> Mikes Bait and Tackle Shop</p> How to load a script from a different web server <script type="text/javascript"> src="http://www.google-analytics.com/urchin.js"> </script>Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 23
    • How to use the noscript tag in the body section <script type="text/javascript"> var today = new Date(); document.writeln( today.getFullYear() ); </script> <noscript>2009</noscript>Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 24
    • Agenda • Basic JavaScript skills ⇒ How to including JavaScript ⇒ How to code JavaScript statements • How to use objects • How to code control statements • How to create and use functionsMurach’s JavaScript, C5 © 2009, Mike Murach & Associates, Inc. Slide 25
    • The basic syntax rules for JavaScript • JavaScript is case-sensitive. • JavaScript statements end with a semicolon (;). • JavaScript ignores extra whitespace in statements. • Single-line comments begin with two forward slashes (//). • Multi-line comments begin with /* and end with */.Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 26
    • A bit more on StatementsStatements define what will and how somethingwill be done. Types:• Conditional Statements• Loop Statements• Object Manipulation Statements• Exception Handling Statements• Comment Statements
    • A single-line comment nextYear = thisYear + 1; // Add 1 to this year A multi-line comment /* The following line determines what the next year is by adding 1 to the current year */ nextYear = thisYear + 1;Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 28
    • How to split a statement across multiple lines • Split a statement after an arithmetic or relational operator such as: +, -, *, /, =, ==, >, or <. • Split a statement after an opening brace ( { ), bracket ( [ ), or parenthesis. • Split a statement after a closing brace ( } ). • Do not split a statement after an identifier, a value, or the return keyword. • Do not split a statement after a closing bracket ( ] ) or parenthesis. A split statement that results in an error return "Hello"; A split statement that works correctly nextYear = thisYear + 1;Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 29
    • Agenda • Basic JavaScript skills ⇒ How to including JavaScript ⇒ How to code JavaScript statements ⇒ How to create identifiers • How to use objects • How to code control statements • How to create and use functionsMurach’s JavaScript, C5 © 2009, Mike Murach & Associates, Inc. Slide 30
    • Rules for creating identifiers in JavaScript • Identifiers can only contain letters, numbers, the underscore ( __ ) , and the dollar sign ( $ ). • Identifiers can’t start with a number. • Identifiers are case-sensitive. • Identifiers can be any length. • Identifiers can’t be the same as reserved words. • Avoid using global properties and methods as identifiers. • Avoid using names that are similar to reserved words, global properties, or global methods.Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 31
    • Valid identifiers in JavaScript subtotal index_1 $ taxRate calculate_click $logMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 32
    • Agenda • Basic JavaScript skills ⇒ How to including JavaScript ⇒ How to code JavaScript statements ⇒ How to create identifiers ⇒ Primitive data types • How to use objects • How to code control statements • How to create and use functionsMurach’s JavaScript, C5 © 2009, Mike Murach & Associates, Inc. Slide 33
    • The primitive data types • Number • String • BooleanMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 34
    • Examples of number values 15 // an integer -21 // a negative integer 21.5 // a floating-point value -124.82 // a negative floating-point value -3.7e-9 /* a floating-point value equivalent to -0.0000000037 */Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 35
    • Examples of string values "JavaScript" // a string with double quotes String Data // a string with single quotes "" // an empty stringMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 36
    • How the n escape sequence can be used to start a new line in a string var string_value = "This is the first linenThis is the second line" This results in: This is the first line This is the second lineMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 37
    • The two Boolean values true // equivalent to true, yes, or on false // equivalent to false, no, or offMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 38
    • A bit more on Data TypesComposite Special•Object •Null•Function •Undefined•Array
    • Agenda • Basic JavaScript skills ⇒ How to including JavaScript ⇒ How to code JavaScript statements ⇒ How to create identifiers ⇒ Primitive data types ⇒ How to code numeric & string expressions • How to use objects • How to code control statements • How to create and use functionsMurach’s JavaScript, C5 © 2009, Mike Murach & Associates, Inc. Slide 40
    • A bit more on ExpressionsAn Expression assign a value to a variable. Types:• Arithmetic• String• Logical• Object
    • Common arithmetic operators + Addition - Subtraction * Multiplication / Division % Modulus ++ Increment by 1 -- Decrement by 1Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 42
    • String operators + ConcatenationMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 43
    • The order of precedence for arithmetic expressions Order Operators 1 ++ 2 -- 3 * / % 4 + -Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 44
    • Precedence and the use of parentheses 3 + 4 * 5 // Result is 23 (3 + 4) * 5 // Result is 35 13 % 4 + 9 // Result is 10 13 % (4 + 9) // Result is 0Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 45
    • Agenda • Basic JavaScript skills ⇒ How to including JavaScript ⇒ How to code JavaScript statements ⇒ How to create identifiers ⇒ Primitive data types ⇒ How to code numeric & string expressions ⇒ How to declare variables & assign values • How to use objects • How to code control statements • How to create and use functionsMurach’s JavaScript, C5 © 2009, Mike Murach & Associates, Inc. Slide 46
    • How to declare variables without assigning values to them var subtotal; // declares a variable named subtotal var lastName, state, zipCode; // declares three variablesMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 47
    • The assignment operators = Assigns resultsMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 48
    • How to declare variables and assign values var subtotal = 74.95; // subtotal is 74.95 var salesTax = subtotal * .1; // salesTax is 7.495 var isValid = false; // Boolean value is false var zipCode = "93711", state = "CA"; // two assignments var firstName = "Ray", lastName = "Harris"; var fullName = lastName + ", " + firstName; // fullName is "Harris, Ray"Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 49
    • Compound assignment operators += Adds results -= Subtract results *= Multiple results /= Divide results %= Stores modulus and resultsMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 50
    • How to code compound assignment statements var subtotal = 24.50; subtotal += 75.50; // subtotal is 100 subtotal *= .9; // subtotal is 90 (100 * .9) var firstName = "Ray", lastName = "Harris"; var fullName = lastName; // fullName is "Harris" fullName += ", "; // fullName is "Harris, " fullName += firstName; // fullName is "Harris, Ray" var months = 120, message = "Months: "; message += months; // message is "Months: 120"Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 51
    • JavaScript Variables are Dynamically TypedAny variable in JavaScript can hold any data type•The data type can change midway through theprogram var month; month = April; month = 12;
    • Agenda • Basic JavaScript skills • How to use objects ⇒ Objects, properties & methods • How to code control statements • How to create and use functionsMurach’s JavaScript, C5 © 2009, Mike Murach & Associates, Inc. Slide 53
    • A little on ObjectsObjects refers to things, such as windows, documents,images, tables, forms, buttons or links, etc.•An object has properties (values) and has methods(functions) associated to that object.
    • Built ins Objects• JavaScript Object Model• Document Object Model• Browser Object Model
    • The syntax for creating a new object new ObjectType() Examples that create new objects var today = new Date(); // creates a Date object var states = new Array(); // creates an Array objectMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 56
    • The syntax for accessing a property of an object objectName.propertyName Examples that access a property of an object window.alert(window.screenX); // Displays the width of the users screen window.location = "http://www.murach.com"; // Loads the murach.com home pageMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 57
    • The syntax for calling a method of an object objectName.methodName(parameters) Examples that call a method of an object var rateTextbox = document.getElementById("rate"); // Stores a reference to the XHTML element // with the id "rate" document.writeln( today.getFullYear() ); // Gets the full year and writes it to the web pageMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 58
    • Examples of object chaining alert( document.getElementById("rate").value ); /* Uses the alert method to display the value property of the DOM object that is returned by the getElementById method. */ alert( window.location.toLowerCase() ); /* Uses the alert method to display the location property of the current page after it has been converted to lowercase letters by the toLowerCase method. */Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 59
    • Agenda• Basic JavaScript skills• How to use objects ⇒ Objects, properties & methods ⇒ How to use window objects & document objects• How to code control statements• How to create and use functions
    • One property of the window object window.location Common methods of the window object window.alert(message) window.prompt(message,default value) window.confirm(message) Common global functions parseInt(string) parseFloat(string)Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 61
    • Examples that use these properties and methods window.alert("Invalid entry."); // displays "Invalid entry." var userEntry = prompt(errorMessage,100); // accepts user entry parseInt("12345.67"); // returns the integer 12345 parseFloat("12345.67"); // returns the floating point value 12345.67 parseFloat("Ray Harris"); // returns NaNMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 62
    • Common methods of the document object document.getElementById(id) document.write(text) document.writeln(text) Examples that use these methods var rateTextbox = document.getElementById("rate"); /* gets the DOM object that represents the HTML element with "rate" as its id and stores it in a variable named rateTextbox. */ document.writeln(message); // writes the string in the message variable to the documentMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 63
    • Notes on using the window and document objects • The window object is the global object when JavaScript is used in a web browser. • JavaScript lets you omit the object name and period when referring to the window object. • The document object is the object that allows you to work with the DOM.Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 64
    • Agenda • Basic JavaScript skills • How to use objects ⇒ Objects, properties & methods ⇒ How to use window objects & document objects ⇒ How to use number, strings, & date objects • How to code control statements • How to create and use functionsMurach’s JavaScript, C5 © 2009, Mike Murach & Associates, Inc. Slide 65
    • One method of the Number object object.toFixed(digits) Examples var balance = 2384.55678; // creates a number object named balance window.alert ( balance.toFixed(2) ); // displays 2384.56 // balance is still 2384.55678 balance = parseFloat( balance.toFixed(2) ); // balance is now 2384.56Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 66
    • Methods of the String object object.substr(start,length) object.toLowerCase() object.toUpperCase() Examples var guest = "Ray Harris"; // creates a string object named guest window.alert ( guest.toUpperCase() ); // displays "RAY HARRIS" window.alert ( guest.substr(0,3) ); // displays "Ray" guest = guest.substr(4,6); // guest is now "Harris"Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 67
    • Methods of the Date object object.toDateString() object.getMonth() object.getDate() object.getFullYear() Examples var today = new Date(); // creates a Date object named today window.alert ( today.toDateString() ); // assume the current date is 09/20/2008 // displays Sat Sep 20 2008 window.alert ( today.getFullYear() ); // displays 2008 window.alert ( today.getMonth() ); // displays 8, not 9, for SeptemberMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 68
    • Agenda• Basic JavaScript skills• How to use objects ⇒ Objects, properties & methods ⇒ How to use window objects & document objects ⇒ How to use number, strings, & date objects ⇒ How to get & display with a Textbox object• How to code control statements• How to create and use functions
    • Common properties of the Textbox object object.value object.disabled Two XHTML <input> tags that create text boxes <input type="text" id="rate" /> <input type="text" id="salesTax" disabled="disabled" /> How to get the text box value in two statements var rateTextbox = document.getElementById("rate"); // Store a reference to the text box var rate = parseFloat( rateTextbox.value ); // Get the value and convert it to a number How to get the value with object chaining var rate = parseFloat(document.getElementById("rate").value);Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 70
    • How to enable a text box document.getElementById("salesTax").disabled = false; How to display a value in a text box document.getElementById("salesTax").value = ""; // Assign an empty string to a text box document.getElementById("salesTax").value = salesTax.toFixed(2); /* Assign the value of a variable named salesTax to a text box */Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 71
    • One method of the Textbox object object.focus() How to move the cursor to a text box document.getElementById("investment").focus();Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 72
    • Agenda• Basic JavaScript skills• How to use objects• How to code control statements ⇒ How to code conditional expressions• How to create and use functions
    • The relational operators == Equal != Not equal < Less than <= Less than or equal to > Greater than >= Greater than or equal toMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 74
    • The syntax of the global isNaN function isNaN(expression) Examples of the global isNaN function isNaN("Harris") // Returns true since "Harris" is not a number isNaN("123.45") // Returns false since "123.45" // can be converted to a numberMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 75
    • The logical operators in order of precedence Operator Description ! NOT && AND || OR How the logical operators work • Both tests with the AND operator must be true for the overall test to be true. • At least one test with the OR operator must be true for the overall test to be true. • The NOT operator switches the result of the expression to the other Boolean value.Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 76
    • One common programming Programmer error • Confusing the assignment operator ( = ) with the equality operator ( ==).Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 77
    • More common Programmer errors1. Missing quotations marks for strings2. Mismatching single/double quotation marks3. Referencing objects that don’t yet exists4. Using methods with objects that don’t support those methods5. Using proper identifiers6. Proper placement Adapted from www.javascriptsource.com/debug
    • Agenda• Basic JavaScript skills• How to use objects• How to code control statements ⇒ How to code conditional expressions ⇒ How to code if statement• How to create and use functions
    • If…thenSelection between alternatecourses of action depends True False conditionupon the evaluation of acondition statement statement block 1 block 2
    • An if statement with an else clause if ( age >= 18 ) { alert ("You may vote."); } else { alert ("You are not old enough to vote."); } An if statement with else if and else clauses if ( isNaN(rate) ) { alert ("You did not provide a number for the rate."); } else if ( rate < 0 ) { alert ("The rate may not be less than zero."); } else { alert ("The rate is: " + rate + "."); }Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 81
    • An if statement with a compound conditional expression if ( isNaN(userEntry) || userEntry <= 0 ) { alert ("Please enter a valid number > zero."); } An if statement that tests a Boolean value if ( invalidFlag ) { alert ("All entries must be numeric values > 0."); }Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 82
    • A nested if statement if ( isNaN(totalMonths) || totalMonths <= 0 ) { alert ("Please enter a number of months > zero."); } else { var years = parseInt ( totalMonths / 12 ); var months = totalMonths % 12; if ( years == 0 ) { alert ( "The investment time is " + months + " months."); } else if ( months == 0 ) { alert ( "The investment time is " + years + " years."); } else { var message = "The investment time is " + years + " years "; message += "and " + months + " months."; alert(message); } }Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 83
    • Agenda• Basic JavaScript skills• How to use objects• How to code control statements ⇒ How to code conditional expressions ⇒ How to code if statements ⇒ How to code while and for statements• How to create and use functions
    • for / while Loop through statement block as long as a condition is truestatement True condition block False
    • A while loop that adds 1 through 5 var sumOfNumbers = 0; var loops = 5; var counter = 1; while (counter <= loops) { sumOfNumbers += counter; counter++; } alert(sumOfNumbers); // displays 15 A for loop that adds 1 through 5 var sumOfNumbers = 0; var loops = 5; for (var counter = 1; counter <= loops; counter++) { sumOfNumbers += counter; } alert(sumOfNumbers); // displays 15Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 86
    • A while loop that gets a user entry userEntry = prompt("Please enter a number:", 100); while ( isNaN( userEntry ) ) { alert( "You did not enter a number."); userEntry = prompt("Please enter a number:", 100); }A for loop that calculates the future valueof a monthly investment var monthlyInvestment = 100; // investment is $100 var monthlyRate = .01; // interest rate is 12% var months = 120; // 120 months is 10 years var futureValue = 0; // futureValue starts at 0 for ( i = 1; i <= months; i++ ) { futureValue = ( futureValue + monthlyInvestment ) * (1 + monthlyRate); }Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 87
    • Agenda• Basic JavaScript skills• How to use objects• How to code control statements• How to create and use functions ⇒ How to create and call a function
    • What is a Function?A set of statements that return reliableresults.Also known as subprogram, procedure,subroutine 89
    • Calling a functionThere are two common ways to call a function: 1. From another function
    • A function with no parameters var showYear = function () { var today = new Date(); alert( today.getFullYear() ); } How to call a function that doesn’t return a value showYear(); // displays the current yearMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 91
    • A function with one parameter that returns a value var $ = function ( id ) { return document.getElementById( id ); } How to call a function that returns a value var taxRate = $("taxRate");Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 92
    • A function with two parameters that doesn’t return a value var displayEmail = function ( username, domain ) { document.write( username + "@" + domain); } How to call a function with two parameters that doesn’t return a value displayEmail( "mike", "murach.com");Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 93
    • A function with two parameters that returns a value var calculateTax = function ( subtotal, taxRate ) { var tax = subtotal * taxRate; tax = parseFloat( tax.toFixed(2) ); return tax; } How to call a function with two parameters that returns a value var subtotal = 74.95; var taxRate = 0.07; var salesTax = calculateTax( subtotal, taxRate ); // returns 5.25Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 94
    • Agenda• Basic JavaScript skills• How to use objects• How to code control statements• How to create and use functions ⇒ How to create and call a function ⇒ How to code an event handler
    • Calling a function• There are two common ways to call a function: 1. From another function 2. From an event
    • Common events Object Event button onclick window onloadMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 97
    • An application with an onclick event handler <head> <script type="text/javascript"> // This function receives an id and returns an XHTML object. var $ = function ( id ) { return document.getElementById( id ); } // This is the onclick event handler named display_click. var display_click = function () { alert( "You clicked the button."); } // This is the onload event handler that assigns the // display_click handler to the click event of the button. window.onload = function () { $("btnDisplay").onclick = display_click; } </script> </head> <body> <p><input type="button" value="Display Message" id="btnDisplay" /></p>Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 98
    • The web browser after the Display Message button is clickedMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 99
    • Exercise #2
    • Add External link (head section)<link rel="stylesheet" href="css/future_value.css" /><script src="js/future_value.js"></script>
    • The future_value.html (body section)<div id="buttons"><label>&nbsp;</label><input type="button" id="calculate" value="calculate"onclick="calculate_click()"/><br /></div>
    • display_results.php// get the data from the form$investment = $_POST[investment];$interest_rate = $_POST[interest_rate];$years = $_POST[years];// validate investment entryif ( empty($investment) ) { $error_message = Investment is a required field.;} else if ( !is_numeric($investment) ) { $error_message = Investment must be a valid number.;} else if ( $investment <= 0 ) { $error_message = Investment must be greater than zero.;
    • display_results.php// validate interest rate entry} else if ( empty($interest_rate) ) { $error_message = Interest rate is a required field.;} else if ( !is_numeric($interest_rate) ) { $error_message = Interest rate must be a valid number.;} else if ( $interest_rate <= 0 ) { $error_message = Interest rate must be greater than zero.; // set error message to empty string} else { $error_message = ; }// if an error message exists, go to the index pageif ($error_message != ) { include(index.php); exit(); }
    • The first page with an error messageMurachs PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 105
    • display_results.php// calculate the future value$future_value = $investment;for ($i = 1; $i <= $years; $i++) { $future_value = ($future_value + ( $future_value * $interest_rate * .01));// apply currency and percent formatting$investment_f = $.number_format($investment, 2);$yearly_rate_f = $interest_rate.%;$future_value_f = $.number_format($future_value, 2);
    • js/future_value.js// Create main calculation function // Get the user entries from the first three text boxes // Set output text box value to be an empty string // Test the three input values for validity // Calculate future value // Return output rounded to 2 decimal places// Auto load focus
    • js/future_value.js// Create main calculation functioncalculate_click = function () { // Get the user entries from the first three text boxes // Return output rounded to 2 decimal places}// Auto load focus
    • js/future_value.js// Get the user entries from the first three text boxesvar $investment;var $investment = document.getElementById("investment").value;var $investment = parseFloat( $investment );var $interest_rate;var $interest_rate = document.getElementById("interest_rate").value;var $interest_rate = parseFloat( $interest_rate );var $years;var $years = document.getElementById("years").value;var $years = parseFloat( $years );
    • js/future_value.js//Set output text box value to be an empty stringdocument.getElementById("future_value").value = "";
    • js/future_value.js// Test the three input values for validityif (isNaN($investment) || $investment <= 0) { alert("Investment must be a valid numbernand greater than zero.");} else if(isNaN($interest_rate) || $interest_rate <= 0) { alert("Rate must be a valid numbernand greater than zero.");} else if(isNaN($years) || $years <= 0) { alert("Years must be a valid numbernand greater than zero.");} else {//calculate future value//return output rounded to 2 decimal places}
    • js/future_value.js// calculate future valuevar $future_value = $investment;for (var $i = 1; $i <= $years; $i++) { $future_value = ($future_value + ( $future_value * $interest_rate * .01)); }
    • What the loop is doing
    • js/future_value.js} else {//calculate future value//return output rounded to 2 decimal placesdocument.getElementById("future_value").value = $future_value.toFixed(2);}
    • js/future_value.js// auto load focuswindow.onload = function () { document.getElementById("investment").focus();}03/04/12 6:00 PM Slide 1
    • Pop QuizTrue or False: Can I declare a variable, obtaininput and convert to a floating point numericalvalue all at once?
    • Pop QuizTrue via object chaining // Get the user entries from the first three text boxes var $investment = parseFloat ( document.getElementById("investment").value ); var $interest_rate = parseFloat( document.getElementById("interest_rate").value ); var $years = parseFloat ( document.getElementById("years").value );
    • Murach’s uses a JavaScript helper function/* Create a $ helper function that returns any DOM elementvalue */var $ = function (id) { return document.getElementById(id);}/* Get the data from the user by calling the $ helperfunction */var investment = parseFloat( $("investment").value );var annualRate = parseFloat( $("rate").value );var years = parseInt( $("years").value );/* Set the intial value of the fourth text box to be anempty string by calling the $ helper function */$("future_value").value = "";
    • Replace JavaScript Function with HTML5 attribute// auto load focuswindow.onload = function () { document.getElementById("investment").focus();}<label for="investment">Investment:</label><input type="text" name="investment" id="investment" autofocus /><br /-->
    • Homework• Submit a brief essay on which do you prefer – client side scripting versus server side scripting and why?• Read JavaScript chapters 6 ,7, 8