SlideShare une entreprise Scribd logo
1  sur  120
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 the
Experience
Exercise #1
Design by fiat
“I read about JavaScript and it’s
really cool. So let’s refactor the
future value app. Do me a favor,
make the background orange…I’m
a huge Jeremy Lin fan.”
Chapter 2

                       How to code
                    a PHP application



Murach's PHP and MySQL, C2   © 2010, Mike Murach & Associates, Inc.   Slide 6
The first page




Murach's PHP and MySQL, C2   © 2010, Mike Murach & Associates, Inc.   Slide 7
The second page




Murach's 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.css
body {
    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 much
expressive power that you
can get a lot done without
knowing 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

                     Proprietary


JScript 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


                       Standard

ECMAScript is based on JavaScript, Jscript, and
ActionScript
•ECMA-262 5th edition codifies de facto interpretations of
the language specification that have become common
among 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 appropriate




Murach’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>
      Mike's 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 functions




Murach’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 Statements
Statements define what will and how something
will 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 functions




Murach’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
           $log




Murach’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 functions




Murach’s JavaScript, C5           © 2009, Mike Murach & Associates, Inc.
                                                                           Slide 33
The primitive data types

       • Number
       • String
       • Boolean




Murach’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 string




Murach’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 line




Murach’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 off




Murach’s JavaScript, C2           © 2009, Mike Murach & Associates, Inc.
                                                                           Slide 38
A bit more on Data Types
Composite         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 functions




Murach’s JavaScript, C5           © 2009, Mike Murach & Associates, Inc.
                                                                           Slide 40
A bit more on Expressions
An 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 1




Murach’s JavaScript, C2           © 2009, Mike Murach & Associates, Inc.
                                                                           Slide 42
String operators
        +                 Concatenation




Murach’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 0




Murach’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 functions




Murach’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 variables




Murach’s JavaScript, C2     © 2009, Mike Murach & Associates, Inc.
                                                                     Slide 47
The assignment operators
            =             Assigns results




Murach’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 results




Murach’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 Typed
Any variable in JavaScript can hold any data type
•The data type can change midway through the
program


           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 functions




Murach’s JavaScript, C5             © 2009, Mike Murach & Associates, Inc.
                                                                             Slide 53
A little on Objects
Objects 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 object




Murach’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 user's screen

           window.location = "http://www.murach.com";
           // Loads the murach.com home page




Murach’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 page




Murach’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 NaN




Murach’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 document




Murach’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 functions




Murach’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.56




Murach’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 September


Murach’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 to




Murach’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 number




Murach’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 errors
1. Missing quotations marks for strings
2. Mismatching single/double quotation marks
3. Referencing objects that don’t yet exists
4. Using methods with objects that don’t support those
   methods
5. Using proper identifiers
6. 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…then


Selection between alternate
courses of action depends       True                   False
                                          condition
upon the evaluation of a
condition

                              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 true




statement   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 15



Murach’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 value
of 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 reliable
results.

Also known as subprogram, procedure,
subroutine




                                           89
Calling a function
There 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 year




Murach’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.25




Murach’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       onload




Murach’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 clicked




Murach’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 entry
if ( 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 page
if ($error_message != '') {
    include('index.php');
        exit(); }
The first page with an error message




Murach's 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 function
calculate_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 boxes
var $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 string
document.getElementById("future_value").value = "";
js/future_value.js
// Test the three input values for validity
if (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 value
var $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 places
document.getElementById("future_value").value =
    $future_value.toFixed(2);
}
js/future_value.js
// auto load focus
window.onload = function () {
   document.getElementById("investment").focus();
}




03/04/12 6:00 PM                                    Slide 1
Pop Quiz
True or False: Can I declare a variable, obtain
input and convert to a floating point numerical
value all at once?
Pop Quiz
True 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 element
value */
var $ = function (id) {
    return document.getElementById(id);
}

/* Get the data from the user by calling the $ helper
function */
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 an
empty string by calling the $ helper function */
$("future_value").value = "";
Replace JavaScript Function with HTML5 attribute

// auto load focus
window.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

Contenu connexe

En vedette

田舎から見るWordPressイベント総括2010
田舎から見るWordPressイベント総括2010田舎から見るWordPressイベント総括2010
田舎から見るWordPressイベント総括2010Hideki Masuoka
 
ระบบดูแลช่วยเหลือนักเรียน
ระบบดูแลช่วยเหลือนักเรียนระบบดูแลช่วยเหลือนักเรียน
ระบบดูแลช่วยเหลือนักเรียนnuywena2520
 
Week 4
Week 4Week 4
Week 4A VD
 
Venid a mí todos los que estáis trabajados y cargados
Venid a mí todos los que estáis trabajados y cargadosVenid a mí todos los que estáis trabajados y cargados
Venid a mí todos los que estáis trabajados y cargadosmisionero2000
 
สารสนเทศโรงเรียนบ้านแบง
สารสนเทศโรงเรียนบ้านแบงสารสนเทศโรงเรียนบ้านแบง
สารสนเทศโรงเรียนบ้านแบงSIRIMAUAN
 
عرض ورقة عمل «رؤيتنا»
عرض ورقة عمل «رؤيتنا»عرض ورقة عمل «رؤيتنا»
عرض ورقة عمل «رؤيتنا»bahrainhistory
 

En vedette (6)

田舎から見るWordPressイベント総括2010
田舎から見るWordPressイベント総括2010田舎から見るWordPressイベント総括2010
田舎から見るWordPressイベント総括2010
 
ระบบดูแลช่วยเหลือนักเรียน
ระบบดูแลช่วยเหลือนักเรียนระบบดูแลช่วยเหลือนักเรียน
ระบบดูแลช่วยเหลือนักเรียน
 
Week 4
Week 4Week 4
Week 4
 
Venid a mí todos los que estáis trabajados y cargados
Venid a mí todos los que estáis trabajados y cargadosVenid a mí todos los que estáis trabajados y cargados
Venid a mí todos los que estáis trabajados y cargados
 
สารสนเทศโรงเรียนบ้านแบง
สารสนเทศโรงเรียนบ้านแบงสารสนเทศโรงเรียนบ้านแบง
สารสนเทศโรงเรียนบ้านแบง
 
عرض ورقة عمل «رؤيتنا»
عرض ورقة عمل «رؤيتنا»عرض ورقة عمل «رؤيتنا»
عرض ورقة عمل «رؤيتنا»
 

Similaire à Week 7

Week 2
Week 2Week 2
Week 2A VD
 
8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentationJohnLagman3
 
Javascript - Ebook (A Quick Guide)
Javascript - Ebook (A Quick Guide)Javascript - Ebook (A Quick Guide)
Javascript - Ebook (A Quick Guide)sourav newatia
 
JavaScript Framework Smackdown
JavaScript Framework SmackdownJavaScript Framework Smackdown
JavaScript Framework Smackdownmeghantaylor
 
getting started with java script
 getting started with java script  getting started with java script
getting started with java script Kopi Maheswaran
 
Iwt note(module 2)
Iwt note(module 2)Iwt note(module 2)
Iwt note(module 2)SANTOSH RATH
 
MCA-202-W4-L1.pptx
MCA-202-W4-L1.pptxMCA-202-W4-L1.pptx
MCA-202-W4-L1.pptxmanju451965
 
Getting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with ThymeleafGetting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with ThymeleafMasatoshi Tada
 
JavaScript Interview Questions with Answers
JavaScript Interview Questions with AnswersJavaScript Interview Questions with Answers
JavaScript Interview Questions with AnswersAK Deep Knowledge
 
WWW/Internet 2011 - A Framework for Web 2.0 Secure Widgets
WWW/Internet 2011 - A Framework for Web 2.0 Secure WidgetsWWW/Internet 2011 - A Framework for Web 2.0 Secure Widgets
WWW/Internet 2011 - A Framework for Web 2.0 Secure WidgetsVagner Santana
 
Introduction to MVC in Flex and HydraMVC
Introduction to MVC in Flex and HydraMVCIntroduction to MVC in Flex and HydraMVC
Introduction to MVC in Flex and HydraMVCcltru
 
WEB MODULE 3.pdf
WEB MODULE 3.pdfWEB MODULE 3.pdf
WEB MODULE 3.pdfDeepika A B
 
Java script
Java scriptJava script
Java scriptKumar
 
Java script tutorial by example
Java script tutorial by exampleJava script tutorial by example
Java script tutorial by examplemyzyzy
 
Unit 4 Java script.pptx
Unit 4 Java script.pptxUnit 4 Java script.pptx
Unit 4 Java script.pptxGangesh8
 

Similaire à Week 7 (20)

Week 2
Week 2Week 2
Week 2
 
8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation
 
Javascript - Ebook (A Quick Guide)
Javascript - Ebook (A Quick Guide)Javascript - Ebook (A Quick Guide)
Javascript - Ebook (A Quick Guide)
 
JavaScript Framework Smackdown
JavaScript Framework SmackdownJavaScript Framework Smackdown
JavaScript Framework Smackdown
 
getting started with java script
 getting started with java script  getting started with java script
getting started with java script
 
Iwt note(module 2)
Iwt note(module 2)Iwt note(module 2)
Iwt note(module 2)
 
MCA-202-W4-L1.pptx
MCA-202-W4-L1.pptxMCA-202-W4-L1.pptx
MCA-202-W4-L1.pptx
 
IP Unit 2.pptx
IP Unit 2.pptxIP Unit 2.pptx
IP Unit 2.pptx
 
Getting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with ThymeleafGetting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with Thymeleaf
 
JavaScript Interview Questions with Answers
JavaScript Interview Questions with AnswersJavaScript Interview Questions with Answers
JavaScript Interview Questions with Answers
 
WWW/Internet 2011 - A Framework for Web 2.0 Secure Widgets
WWW/Internet 2011 - A Framework for Web 2.0 Secure WidgetsWWW/Internet 2011 - A Framework for Web 2.0 Secure Widgets
WWW/Internet 2011 - A Framework for Web 2.0 Secure Widgets
 
Introduction to MVC in Flex and HydraMVC
Introduction to MVC in Flex and HydraMVCIntroduction to MVC in Flex and HydraMVC
Introduction to MVC in Flex and HydraMVC
 
Javascript tutorial
Javascript tutorialJavascript tutorial
Javascript tutorial
 
WEB MODULE 3.pdf
WEB MODULE 3.pdfWEB MODULE 3.pdf
WEB MODULE 3.pdf
 
web designing course bangalore
web designing course bangaloreweb designing course bangalore
web designing course bangalore
 
Java script
Java scriptJava script
Java script
 
p032-26
p032-26p032-26
p032-26
 
p032-26
p032-26p032-26
p032-26
 
Java script tutorial by example
Java script tutorial by exampleJava script tutorial by example
Java script tutorial by example
 
Unit 4 Java script.pptx
Unit 4 Java script.pptxUnit 4 Java script.pptx
Unit 4 Java script.pptx
 

Plus de A VD

Week 8
Week 8Week 8
Week 8A VD
 
Contest
ContestContest
ContestA VD
 
Week 6
Week 6Week 6
Week 6A VD
 
Part 2
Part 2Part 2
Part 2A VD
 
Week 5
Week 5Week 5
Week 5A VD
 
Intro toprogramming part2
Intro toprogramming part2Intro toprogramming part2
Intro toprogramming part2A VD
 
Week 5
Week 5Week 5
Week 5A VD
 
Week 3
Week 3Week 3
Week 3A VD
 
Week 1
Week 1Week 1
Week 1A VD
 

Plus de A VD (9)

Week 8
Week 8Week 8
Week 8
 
Contest
ContestContest
Contest
 
Week 6
Week 6Week 6
Week 6
 
Part 2
Part 2Part 2
Part 2
 
Week 5
Week 5Week 5
Week 5
 
Intro toprogramming part2
Intro toprogramming part2Intro toprogramming part2
Intro toprogramming part2
 
Week 5
Week 5Week 5
Week 5
 
Week 3
Week 3Week 3
Week 3
 
Week 1
Week 1Week 1
Week 1
 

Dernier

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 

Dernier (20)

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 

Week 7

  • 1.
  • 2. 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
  • 3. 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 the Experience
  • 5. Design by fiat “I read about JavaScript and it’s really cool. So let’s refactor the future value app. Do me a favor, make the background orange…I’m a huge Jeremy Lin fan.”
  • 6. Chapter 2 How to code a PHP application Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 6
  • 7. The first page Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 7
  • 8. The second page Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 8
  • 9. 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 />
  • 10. 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>
  • 11. From main.css to css/future_value.css body { 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; }
  • 12. 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; }
  • 13. What we have so far
  • 14.
  • 15. The world’s most misunderstood programming language “JavaScript has so much expressive power that you can get a lot done without knowing what your doing.” --Douglas Crockford
  • 16. 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
  • 17. Scripting Languages and the First Browser War JavaScript JScript Sept 1995 Nov 1996 Proprietary JScript is identical to JavaScript but… •Some JavaScript commands not supported in JScript •Some JScript commands not supported in JavaScript
  • 18. European Computer Manufacturing Association Takes Over ECMAScript Jun 1997 Standard ECMAScript is based on JavaScript, Jscript, and ActionScript •ECMA-262 5th edition codifies de facto interpretations of the language specification that have become common among browsers
  • 19. Chapter 2 How to code a JavaScript application* Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 19
  • 20. *Updates for this class • XHMTL rules supersede by HTML5 and will be noted where appropriate Murach’s JavaScript, C4 © 2009, Mike Murach & Associates, Inc. Slide 20
  • 21. Agenda • Basic JavaScript skills ⇒ How to include JavaScript • How to use objects • How to code control statements • How to create and use functions
  • 22. 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
  • 23. How to embed JavaScript in the body section <p>&copy; <script type="text/javascript"> var today = new Date(); document.writeln( today.getFullYear() ); </script> Mike's 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
  • 24. 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
  • 25. 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 functions Murach’s JavaScript, C5 © 2009, Mike Murach & Associates, Inc. Slide 25
  • 26. 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
  • 27. A bit more on Statements Statements define what will and how something will be done. Types: • Conditional Statements • Loop Statements • Object Manipulation Statements • Exception Handling Statements • Comment Statements
  • 28. 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
  • 29. 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
  • 30. 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 functions Murach’s JavaScript, C5 © 2009, Mike Murach & Associates, Inc. Slide 30
  • 31. 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
  • 32. Valid identifiers in JavaScript subtotal index_1 $ taxRate calculate_click $log Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 32
  • 33. 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 functions Murach’s JavaScript, C5 © 2009, Mike Murach & Associates, Inc. Slide 33
  • 34. The primitive data types • Number • String • Boolean Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 34
  • 35. 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
  • 36. Examples of string values "JavaScript" // a string with double quotes 'String Data' // a string with single quotes "" // an empty string Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 36
  • 37. 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 line Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 37
  • 38. The two Boolean values true // equivalent to true, yes, or on false // equivalent to false, no, or off Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 38
  • 39. A bit more on Data Types Composite Special •Object •Null •Function •Undefined •Array
  • 40. 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 functions Murach’s JavaScript, C5 © 2009, Mike Murach & Associates, Inc. Slide 40
  • 41. A bit more on Expressions An Expression assign a value to a variable. Types: • Arithmetic • String • Logical • Object
  • 42. Common arithmetic operators + Addition - Subtraction * Multiplication / Division % Modulus ++ Increment by 1 -- Decrement by 1 Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 42
  • 43. String operators + Concatenation Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 43
  • 44. The order of precedence for arithmetic expressions Order Operators 1 ++ 2 -- 3 * / % 4 + - Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 44
  • 45. 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 0 Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 45
  • 46. 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 functions Murach’s JavaScript, C5 © 2009, Mike Murach & Associates, Inc. Slide 46
  • 47. How to declare variables without assigning values to them var subtotal; // declares a variable named subtotal var lastName, state, zipCode; // declares three variables Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 47
  • 48. The assignment operators = Assigns results Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 48
  • 49. 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
  • 50. Compound assignment operators += Adds results -= Subtract results *= Multiple results /= Divide results %= Stores modulus and results Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 50
  • 51. 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
  • 52. JavaScript Variables are Dynamically Typed Any variable in JavaScript can hold any data type •The data type can change midway through the program var month; month = April; month = 12;
  • 53. Agenda • Basic JavaScript skills • How to use objects ⇒ Objects, properties & methods • How to code control statements • How to create and use functions Murach’s JavaScript, C5 © 2009, Mike Murach & Associates, Inc. Slide 53
  • 54. A little on Objects Objects 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.
  • 55. Built ins Objects • JavaScript Object Model • Document Object Model • Browser Object Model
  • 56. 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 object Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 56
  • 57. 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 user's screen window.location = "http://www.murach.com"; // Loads the murach.com home page Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 57
  • 58. 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 page Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 58
  • 59. 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
  • 60. 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
  • 61. 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
  • 62. 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 NaN Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 62
  • 63. 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 document Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 63
  • 64. 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
  • 65. 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 functions Murach’s JavaScript, C5 © 2009, Mike Murach & Associates, Inc. Slide 65
  • 66. 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.56 Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 66
  • 67. 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
  • 68. 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 September Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 68
  • 69. 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
  • 70. 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
  • 71. 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
  • 72. 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
  • 73. Agenda • Basic JavaScript skills • How to use objects • How to code control statements ⇒ How to code conditional expressions • How to create and use functions
  • 74. The relational operators == Equal != Not equal < Less than <= Less than or equal to > Greater than >= Greater than or equal to Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 74
  • 75. 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 number Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 75
  • 76. 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
  • 77. One common programming Programmer error • Confusing the assignment operator ( = ) with the equality operator ( ==). Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 77
  • 78. More common Programmer errors 1. Missing quotations marks for strings 2. Mismatching single/double quotation marks 3. Referencing objects that don’t yet exists 4. Using methods with objects that don’t support those methods 5. Using proper identifiers 6. Proper placement Adapted from www.javascriptsource.com/debug
  • 79. 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
  • 80. If…then Selection between alternate courses of action depends True False condition upon the evaluation of a condition statement statement block 1 block 2
  • 81. 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
  • 82. 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
  • 83. 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
  • 84. 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
  • 85. for / while Loop through statement block as long as a condition is true statement True condition block False
  • 86. 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 15 Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 86
  • 87. 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 value of 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
  • 88. 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
  • 89. What is a Function? A set of statements that return reliable results. Also known as subprogram, procedure, subroutine 89
  • 90. Calling a function There are two common ways to call a function: 1. From another function
  • 91. 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 year Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 91
  • 92. 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
  • 93. 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
  • 94. 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.25 Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 94
  • 95. 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
  • 96. Calling a function • There are two common ways to call a function: 1. From another function 2. From an event
  • 97. Common events Object Event button onclick window onload Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 97
  • 98. 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
  • 99. The web browser after the Display Message button is clicked Murach’s JavaScript, C2 © 2009, Mike Murach & Associates, Inc. Slide 99
  • 101. Add External link (head section) <link rel="stylesheet" href="css/future_value.css" /> <script src="js/future_value.js"></script>
  • 102. The future_value.html (body section) <div id="buttons"> <label>&nbsp;</label> <input type="button" id="calculate" value="calculate" onclick="calculate_click()"/><br /> </div>
  • 103. display_results.php // get the data from the form $investment = $_POST['investment']; $interest_rate = $_POST['interest_rate']; $years = $_POST['years']; // validate investment entry if ( 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.';
  • 104. 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 page if ($error_message != '') { include('index.php'); exit(); }
  • 105. The first page with an error message Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 105
  • 106. 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);
  • 107. 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
  • 108. js/future_value.js // Create main calculation function calculate_click = function () { // Get the user entries from the first three text boxes // Return output rounded to 2 decimal places } // Auto load focus
  • 109. js/future_value.js // Get the user entries from the first three text boxes var $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 );
  • 110. js/future_value.js //Set output text box value to be an empty string document.getElementById("future_value").value = "";
  • 111. js/future_value.js // Test the three input values for validity if (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 }
  • 112. js/future_value.js // calculate future value var $future_value = $investment; for (var $i = 1; $i <= $years; $i++) { $future_value = ($future_value + ( $future_value * $interest_rate * .01)); }
  • 113. What the loop is doing
  • 114. js/future_value.js } else { //calculate future value //return output rounded to 2 decimal places document.getElementById("future_value").value = $future_value.toFixed(2); }
  • 115. js/future_value.js // auto load focus window.onload = function () { document.getElementById("investment").focus(); } 03/04/12 6:00 PM Slide 1
  • 116. Pop Quiz True or False: Can I declare a variable, obtain input and convert to a floating point numerical value all at once?
  • 117. Pop Quiz True 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 );
  • 118. Murach’s uses a JavaScript helper function /* Create a $ helper function that returns any DOM element value */ var $ = function (id) { return document.getElementById(id); } /* Get the data from the user by calling the $ helper function */ 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 an empty string by calling the $ helper function */ $("future_value").value = "";
  • 119. Replace JavaScript Function with HTML5 attribute // auto load focus window.onload = function () { document.getElementById("investment").focus(); } <label for="investment">Investment:</label> <input type="text" name="investment" id="investment" autofocus /><br /-->
  • 120. 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