Homework• Submit a brief essay on which do you prefer –  client side scripting versus server side  scripting and why?• Rea...
Web Technology Stack                       Data – What does it know?                       Behavior – What does it do?    ...
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 ...
Chapter 2                       How to code                    a PHP applicationMurachs PHP and MySQL, C2   © 2010, Mike M...
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 ch...
From index.php to future_value.html (continued)     <label for=”interest_rate”>Yearly Interest Rate:</label>     <input ty...
From main.css to css/future_value.cssbody {    font-family: Arial, Helvetica, sans-serif;    background: orange;}#content ...
From main.css to css/future_value.css#data input {    float: left;    width: 15em;    margin-bottom: .5em;}#buttons input ...
What we have so far
The world’s most misunderstood      programming language“JavaScript has so muchexpressive power that youcan get a lot done...
Introduction of JavaScript             JavaScript is an interpreted             programming or script             language...
Scripting Languages and           the First Browser War JavaScript                                JScript Sept 1995       ...
European Computer Manufacturing       Association Takes Over                                               ECMAScript     ...
Chapter 2               How to code a           JavaScript application*Murach’s JavaScript, C2   © 2009, Mike Murach & Ass...
*Updates for this class• XHMTL rules supersede by HTML5 and will be  noted where appropriateMurach’s JavaScript, C4       ...
Agenda• Basic JavaScript skills   ⇒     How to include JavaScript• How to use objects• How to code control statements• How...
How to load JavaScript from an external file         <script type="text/javascript" src="sales_tax.js"></script>         H...
How to embed JavaScript in the body section    <p>&copy;      <script type="text/javascript">        var today = new Date(...
How to use the noscript tag in the body section       <script type="text/javascript">           var today = new Date();   ...
Agenda     • Basic JavaScript skills           ⇒        How to including JavaScript           ⇒        How to code JavaScr...
The basic syntax rules for JavaScript  • JavaScript is case-sensitive.  • JavaScript statements end with a semicolon (;). ...
A bit more on StatementsStatements define what will and how somethingwill be done. Types:• Conditional Statements• Loop St...
A single-line comment                 nextYear = thisYear + 1; // Add 1 to this year           A multi-line comment       ...
How to split a statement across multiple lines          • Split a statement after an arithmetic or relational operator suc...
Agenda     • Basic JavaScript skills           ⇒        How to including JavaScript           ⇒        How to code JavaScr...
Rules for creating identifiers in JavaScript    • Identifiers can only contain letters, numbers, the underscore ( __ ) ,  ...
Valid identifiers in JavaScript           subtotal           index_1           $           taxRate           calculate_cli...
Agenda     • Basic JavaScript skills           ⇒        How to including JavaScript           ⇒        How to code JavaScr...
The primitive data types       • Number       • String       • BooleanMurach’s JavaScript, C2   © 2009, Mike Murach & Asso...
Examples of number values     15                   // an integer     -21                  // a negative integer     21.5  ...
Examples of string values          "JavaScript"    // a string with double quotes          String Data   // a string with ...
How the n escape sequence can be used to start a new line in a string       var string_value = "This is the first linenThi...
The two Boolean values           true           // equivalent to true, yes, or on           false          // equivalent t...
A bit more on Data TypesComposite         Special•Object           •Null•Function         •Undefined•Array
Agenda     • Basic JavaScript skills           ⇒        How to including JavaScript           ⇒        How to code JavaScr...
A bit more on ExpressionsAn Expression assign a value to a variable. Types:• Arithmetic• String• Logical• Object
Common arithmetic operators           +              Addition           -              Subtraction           *            ...
String operators        +                 ConcatenationMurach’s JavaScript, C2            © 2009, Mike Murach & Associates...
The order of precedence for arithmetic        expressions        Order             Operators        1                 ++  ...
Precedence and the use of parentheses     3 + 4 * 5            // Result is 23     (3 + 4) * 5          // Result is 35   ...
Agenda            • Basic JavaScript skills                  ⇒       How to including JavaScript                  ⇒       ...
How to declare variables without assigning             values to them             var subtotal;             // declares a ...
The assignment operators            =             Assigns resultsMurach’s JavaScript, C2          © 2009, Mike Murach & As...
How to declare variables and assign values           var subtotal = 74.95;                     // subtotal is 74.95       ...
Compound assignment operators            +=            Adds results            -=            Subtract results            *...
How to code compound assignment statements      var subtotal = 24.50;      subtotal += 75.50;                 // subtotal ...
JavaScript Variables          are Dynamically TypedAny variable in JavaScript can hold any data type•The data type can cha...
Agenda            • Basic JavaScript skills            • How to use objects               ⇒ Objects, properties & methods ...
A little on ObjectsObjects refers to things, such as windows, documents,images, tables, forms, buttons or links, etc.•An o...
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 =...
The syntax for accessing a property of an object           objectName.propertyName     Examples that access a property of ...
The syntax for calling a method of an object           objectName.methodName(parameters)     Examples that call a method o...
Examples of object chaining           alert( document.getElementById("rate").value );           /* Uses the alert method t...
Agenda• Basic JavaScript skills• How to use objects   ⇒     Objects, properties & methods   ⇒     How to use window object...
One property of the window object            window.location      Common methods of the window object            window.al...
Examples that use these properties and methods            window.alert("Invalid entry.");            // displays "Invalid ...
Common methods of the document object       document.getElementById(id)       document.write(text)       document.writeln(...
Notes on using the window and document objects       • The window object is the global object when JavaScript is used in a...
Agenda            • Basic JavaScript skills            • How to use objects                  ⇒       Objects, properties &...
One method of the Number object           object.toFixed(digits)     Examples           var balance = 2384.55678;         ...
Methods of the String object           object.substr(start,length)           object.toLowerCase()           object.toUpper...
Methods of the Date object              object.toDateString()              object.getMonth()              object.getDate()...
Agenda• Basic JavaScript skills• How to use objects   ⇒     Objects, properties & methods   ⇒     How to use window object...
Common properties of the Textbox object        object.value        object.disabled  Two XHTML <input> tags that create tex...
How to enable a text box                document.getElementById("salesTax").disabled = false;          How to display a va...
One method of the Textbox object           object.focus()     How to move the cursor to a text box           document.getE...
Agenda• Basic JavaScript skills• How to use objects• How to code control statements   ⇒     How to code conditional expres...
The relational operators                      ==   Equal                      !=   Not equal                      <    Les...
The syntax of the global isNaN function           isNaN(expression)     Examples of the global isNaN function           is...
The logical operators in order of precedence     Operator             Description     !                    NOT     &&     ...
One common programming Programmer error  • Confusing the assignment operator ( = ) with the equality    operator ( ==).Mur...
More common Programmer errors1. Missing quotations marks for strings2. Mismatching single/double quotation marks3. Referen...
Agenda• Basic JavaScript skills• How to use objects• How to code control statements   ⇒     How to code conditional expres...
If…thenSelection between alternatecourses of action depends       True                   False                            ...
An if statement with an else clause            if ( age >= 18 ) {                alert ("You may vote.");            } els...
An if statement with a compound          conditional expression                if ( isNaN(userEntry) || userEntry <= 0 ) {...
A nested if statement         if ( isNaN(totalMonths) || totalMonths <= 0 ) {             alert ("Please enter a number of...
Agenda• Basic JavaScript skills• How to use objects• How to code control statements   ⇒     How to code conditional expres...
for / while                                  Loop through statement block                                  as long as a co...
A while loop that adds 1 through 5           var sumOfNumbers = 0;           var loops = 5;           var counter = 1;    ...
A while loop that gets a user entry      userEntry = prompt("Please enter a number:", 100);      while ( isNaN( userEntry ...
Agenda• Basic JavaScript skills• How to use objects• How to code control statements• How to create and use functions   ⇒  ...
What is a Function?A set of statements that return reliableresults.Also known as subprogram, procedure,subroutine         ...
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();               a...
A function with one parameter that returns a value            var $ = function ( id ) {                return document.get...
A function with two parameters          that doesn’t return a value                var displayEmail = function ( username,...
A function with two parameters          that returns a value                var calculateTax = function ( subtotal, taxRat...
Agenda• Basic JavaScript skills• How to use objects• How to code control statements• How to create and use functions   ⇒  ...
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 Java...
An application with an onclick event handler     <head>     <script type="text/javascript">     // This function receives ...
The web browser    after the Display Message button is clickedMurach’s JavaScript, C2   © 2009, Mike Murach & Associates, ...
Exercise #2
Add External link (head section)<link rel="stylesheet" href="css/future_value.css" /><script src="js/future_value.js"></sc...
The future_value.html (body section)<div id="buttons"><label>&nbsp;</label><input type="button" id="calculate" value="calc...
display_results.php// get the data from the form$investment = $_POST[investment];$interest_rate = $_POST[interest_rate];$y...
display_results.php// validate interest rate entry} else if ( empty($interest_rate) ) {    $error_message =       Interest...
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_v...
js/future_value.js// Create main calculation function   // Get the user entries from the first three text boxes   // Set o...
js/future_value.js// Create main calculation functioncalculate_click = function () {    // Get the user entries from the f...
js/future_value.js// Get the user entries from the first three text boxesvar $investment;var $investment = document.getEle...
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("Inves...
js/future_value.js// calculate future valuevar $future_value = $investment;for (var $i = 1; $i <= $years; $i++) {   $futur...
What the loop is doing
js/future_value.js} else {//calculate future value//return output rounded to 2 decimal placesdocument.getElementById("futu...
js/future_value.js// auto load focuswindow.onload = function () {   document.getElementById("investment").focus();}03/04/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 ( ...
Murach’s uses a JavaScript helper function/* Create a $ helper function that returns any DOM elementvalue */var $ = functi...
Replace JavaScript Function with HTML5 attribute// auto load focuswindow.onload = function () {   document.getElementById(...
Homework• Submit a brief essay on which do you prefer –  client side scripting versus server side  scripting and why?• Rea...
Week 7
Week 7
Upcoming SlideShare
Loading in...5
×

Week 7

654

Published on

Week 7

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
654
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
9
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Week 7"

  1. 1. 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
  2. 2. 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
  3. 3. Exercise #1
  4. 4. 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.”
  5. 5. Chapter 2 How to code a PHP applicationMurachs PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 6
  6. 6. The first pageMurachs PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 7
  7. 7. The second pageMurachs PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 8
  8. 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 />
  9. 9. 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>
  10. 10. 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;}
  11. 11. 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;}
  12. 12. What we have so far
  13. 13. The world’s most misunderstood programming language“JavaScript has so muchexpressive power that youcan get a lot done withoutknowing what your doing.” --Douglas Crockford
  14. 14. 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
  15. 15. 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
  16. 16. 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
  17. 17. Chapter 2 How to code a JavaScript application*Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 19
  18. 18. *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
  19. 19. Agenda• Basic JavaScript skills ⇒ How to include JavaScript• How to use objects• How to code control statements• How to create and use functions
  20. 20. 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
  21. 21. 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
  22. 22. 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
  23. 23. 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
  24. 24. 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
  25. 25. 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
  26. 26. 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
  27. 27. 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
  28. 28. 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
  29. 29. 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
  30. 30. Valid identifiers in JavaScript subtotal index_1 $ taxRate calculate_click $logMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 32
  31. 31. 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
  32. 32. The primitive data types • Number • String • BooleanMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 34
  33. 33. 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
  34. 34. 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
  35. 35. 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
  36. 36. 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
  37. 37. A bit more on Data TypesComposite Special•Object •Null•Function •Undefined•Array
  38. 38. 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
  39. 39. A bit more on ExpressionsAn Expression assign a value to a variable. Types:• Arithmetic• String• Logical• Object
  40. 40. Common arithmetic operators + Addition - Subtraction * Multiplication / Division % Modulus ++ Increment by 1 -- Decrement by 1Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 42
  41. 41. String operators + ConcatenationMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 43
  42. 42. The order of precedence for arithmetic expressions Order Operators 1 ++ 2 -- 3 * / % 4 + -Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 44
  43. 43. 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
  44. 44. 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
  45. 45. 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
  46. 46. The assignment operators = Assigns resultsMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 48
  47. 47. 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
  48. 48. 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
  49. 49. 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
  50. 50. 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;
  51. 51. 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
  52. 52. 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.
  53. 53. Built ins Objects• JavaScript Object Model• Document Object Model• Browser Object Model
  54. 54. 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
  55. 55. 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
  56. 56. 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
  57. 57. 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
  58. 58. 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
  59. 59. 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
  60. 60. 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
  61. 61. 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
  62. 62. 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
  63. 63. 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
  64. 64. 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
  65. 65. 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
  66. 66. 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
  67. 67. 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
  68. 68. 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
  69. 69. 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
  70. 70. 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
  71. 71. Agenda• Basic JavaScript skills• How to use objects• How to code control statements ⇒ How to code conditional expressions• How to create and use functions
  72. 72. 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
  73. 73. 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
  74. 74. 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
  75. 75. One common programming Programmer error • Confusing the assignment operator ( = ) with the equality operator ( ==).Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 77
  76. 76. 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
  77. 77. 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
  78. 78. If…thenSelection between alternatecourses of action depends True False conditionupon the evaluation of acondition statement statement block 1 block 2
  79. 79. 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
  80. 80. 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
  81. 81. 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
  82. 82. 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
  83. 83. for / while Loop through statement block as long as a condition is truestatement True condition block False
  84. 84. 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
  85. 85. 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
  86. 86. 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
  87. 87. What is a Function?A set of statements that return reliableresults.Also known as subprogram, procedure,subroutine 89
  88. 88. Calling a functionThere are two common ways to call a function: 1. From another function
  89. 89. 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
  90. 90. 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
  91. 91. 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
  92. 92. 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
  93. 93. 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
  94. 94. Calling a function• There are two common ways to call a function: 1. From another function 2. From an event
  95. 95. Common events Object Event button onclick window onloadMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 97
  96. 96. 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
  97. 97. The web browser after the Display Message button is clickedMurach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 99
  98. 98. Exercise #2
  99. 99. Add External link (head section)<link rel="stylesheet" href="css/future_value.css" /><script src="js/future_value.js"></script>
  100. 100. The future_value.html (body section)<div id="buttons"><label>&nbsp;</label><input type="button" id="calculate" value="calculate"onclick="calculate_click()"/><br /></div>
  101. 101. 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.;
  102. 102. 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(); }
  103. 103. The first page with an error messageMurachs PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 105
  104. 104. 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);
  105. 105. 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
  106. 106. 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
  107. 107. 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 );
  108. 108. js/future_value.js//Set output text box value to be an empty stringdocument.getElementById("future_value").value = "";
  109. 109. 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}
  110. 110. 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)); }
  111. 111. What the loop is doing
  112. 112. js/future_value.js} else {//calculate future value//return output rounded to 2 decimal placesdocument.getElementById("future_value").value = $future_value.toFixed(2);}
  113. 113. js/future_value.js// auto load focuswindow.onload = function () { document.getElementById("investment").focus();}03/04/12 6:00 PM Slide 1
  114. 114. Pop QuizTrue or False: Can I declare a variable, obtaininput and convert to a floating point numericalvalue all at once?
  115. 115. 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 );
  116. 116. 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 = "";
  117. 117. 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 /-->
  118. 118. 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
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×