a javascript application how to code - gavilan...
TRANSCRIPT
![Page 1: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/1.jpg)
How to code a JavaScript application
![Page 2: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/2.jpg)
Objectives
Applied
Using a text editor like Notepad++ or TextWrangler, enter and edit
XHTML, CSS, and JavaScript files.
Using Firefox as your web browser, display any error messages in
the Error Console when you test a JavaScript application.
Given the specifications for a JavaScript application that requires
only the skills and language elements presented in this chapter,
code, test, and debug the application.
![Page 3: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/3.jpg)
Objectives (continued)
Knowledge
Describe the use of the two types of JavaScript comments.
Describe the type of error that can occur if you split a JavaScript
statement in the wrong place.
List the primary rules for creating a JavaScript identifier.
Describe the three primitive data types used in JavaScript.
Describe the use of the \n escape sequence in a string literal.
Describe the rules for evaluating an arithmetic expression,
including order of precedence and the use of parentheses.
Describe the use of variable declarations and assignment
statements.
Describe the use of objects, properties, methods, and object
chaining.
![Page 4: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/4.jpg)
Objectives (continued)
Describe the ways that number, string, Boolean, and Date objects
are created.
Given the name of a common method for a window, document,
Number, String, Boolean, or Textbox object, describe the function
of the method.
Describe the rules for evaluating a conditional expression,
including the use of the isNan function, the order of precedence for
logical operators, and the use of parentheses.
Describe the flow of control for an if, while, or for statement.
Describe the creation and use of functions.
Describe the creation and use of event handlers for the click event
of a button element and the load event of the window object.
![Page 5: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/5.jpg)
Notepad++ with an auto-completion list
![Page 6: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/6.jpg)
Basic skills for using Notepad++
How to open, save, close, and start files
How to change the style for comments
How to use the auto-completion feature
How to let Notepad++ know which language you’re working with
Note
These skills are presented in figure 2-1.
![Page 7: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/7.jpg)
The Sales Tax application in the Firefox browser
![Page 8: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/8.jpg)
How to test a web page
Open the web page in your browser.
Enter the required input data, and run the application.
How to retest a web page
after you change the source code
To reload the edited file for the page, click the Reload or Refresh
button.
![Page 9: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/9.jpg)
If the Reload or Refresh button
doesn’t clear browser memory…
you may need to close the browser window and reopen the
application.
If the application doesn’t do anything when you
test it…
it either has syntax errors or other types of coding errors.
![Page 10: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/10.jpg)
The Firefox Error Console with an error displayed
How to display the Firefox Error Console
Use the ToolsError Console command or press Ctrl+Shift+J.
How to display the source code
Click on the link in the Error Console.
![Page 11: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/11.jpg)
The source code that’s displayed
when you click on the link
![Page 12: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/12.jpg)
How to load JavaScript from an external file <script type="text/javascript" src="sales_tax.js"></script>
How to embed JavaScript
in the head of an XHTML document <head>
...
<script type="text/javascript">
var $ =
function (id) { return document.getElementById(id); }
</script>
...
</head>
![Page 13: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/13.jpg)
How to embed JavaScript
in the body of an HTML document <p>©
<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>
![Page 14: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/14.jpg)
How to use the noscript tag
in the body of an XHTML document <script type="text/javascript">
var today = new Date();
document.writeln( today.getFullYear() );
</script>
<noscript>2009</noscript>
![Page 15: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/15.jpg)
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 */.
![Page 16: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/16.jpg)
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;
![Page 17: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/17.jpg)
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;
![Page 18: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/18.jpg)
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.
![Page 19: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/19.jpg)
Valid identifiers in JavaScript subtotal
index_1
$
taxRate
calculate_click
$log
![Page 20: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/20.jpg)
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
![Page 21: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/21.jpg)
The primitive data types
Number
String
Boolean
Terms
integer
floating-point value
exponent
empty string
escape sequence
Boolean value
![Page 22: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/22.jpg)
Examples of string values "JavaScript" // a string with double quotes
'String Data' // a string with single quotes
"" // an empty string
How the \n escape sequence can be used
to start a new line in a string "A valid variable name\ncannot start with a number."
// represents the string: A valid variable name
// cannot start with a number.
![Page 23: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/23.jpg)
The two Boolean values true // equivalent to true, yes, or on
false // equivalent to false, no, or off
![Page 24: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/24.jpg)
Common arithmetic operators +
-
*
/
%
++
--
![Page 25: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/25.jpg)
The order of precedence
for arithmetic expressions
Order Operators
1 ++
2 --
3 * / %
4 + -
![Page 26: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/26.jpg)
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
![Page 27: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/27.jpg)
Terms
arithmetic expression
arithmetic operator
order of precedence
concatenate
concatenation operator
![Page 28: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/28.jpg)
How to declare variables
without assigning values to them var subtotal;
// declares a variable named subtotal
var lastName, state, zipCode;
// declares three variables
![Page 29: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/29.jpg)
The assignment operators =
+=
-=
*=
/=
%=
![Page 30: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/30.jpg)
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"
![Page 31: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/31.jpg)
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"
![Page 32: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/32.jpg)
Terms
variable
declare a variable
assignment statement
assignment operator
string literal
numeric literal
![Page 33: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/33.jpg)
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
![Page 34: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/34.jpg)
The syntax for accessing a property of an object objectName.propertyName
Examples that access a property of an object alert(window.screenX);
// Displays the width of the user's screen
window.location = "http://www.murach.com";
// Loads the murach.com home page
![Page 35: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/35.jpg)
The syntax for calling a method of an object objectName.methodName(parameters)
Examples that call a method of an object // Stores a reference to the XHTML element
// with the id "rate"
var rateTextbox = document.getElementById("rate");
// Gets the full year and writes it to the web page
document.writeln( today.getFullYear() );
![Page 36: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/36.jpg)
Examples of object chaining // Uses the alert method to display the value property
// of the DOM object that is returned
// by the getElementById method.
alert( document.getElementById("rate").value );
// 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.
alert( window.location.toLowerCase() );
![Page 37: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/37.jpg)
Terms
object
property
method
call a method
parameter (or argument)
object chaining
![Page 38: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/38.jpg)
One property of the window object location
Common methods of the window object alert(message)
prompt(message,default)
parseInt(string)
parseFloat(string)
Examples that use these properties and methods 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
![Page 39: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/39.jpg)
Common methods of the document object getElementById(id)
write(text)
writeln(text)
Examples that use these methods // gets the DOM object that represents
// the XHTML element with "rate" as its id
// and stores it in a variable named rateTextbox
var rateTextbox = document.getElementById("rate");
// writes the string in the message variable to the
document
document.writeln(message);
![Page 40: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/40.jpg)
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.
![Page 41: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/41.jpg)
One method of the Number object toFixed(digits)
Examples var balance = 2384.55678;
// creates a number object named balance
alert ( balance.toFixed(2) );
// displays 2384.56
// balance is still 2384.55678
balance = parseFloat( balance.toFixed(2) );
// balance is now 2384.56
![Page 42: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/42.jpg)
Methods of the String object substr(start,length)
toLowerCase()
toUpperCase()
Examples var guest = "Ray Harris";
// creates a string object named guest
alert ( guest.toUpperCase() ); // displays "RAY HARRIS"
alert ( guest.substr(0,3) ); // displays "Ray"
guest = guest.substr(4,6); // guest is now "Harris"
![Page 43: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/43.jpg)
Methods of the Date object toDateString()
getMonth()
getDate()
getFullYear()
Examples var today = new Date();
// creates a Date object named today
// assume the current date is 09/20/2008
alert ( today.toDateString() );
// displays Sat Sep 20 2008
alert ( today.getFullYear() ); // displays 2008
alert ( today.getMonth() );
// displays 8, not 9, for September
![Page 44: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/44.jpg)
Common properties of the Textbox object value
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 // Store a reference to the text box
var rateTextbox = document.getElementById("rate");
// Get the value and convert it to a number
var rate = parseFloat( rateTextbox.value );
How to get the value with with object chaining var rate =
parseFloat(document.getElementById("rate").value);
![Page 45: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/45.jpg)
How to enable a text box document.getElementById("salesTax").disabled = false;
How to display a value in a text box // Assign an empty string to a text box
document.getElementById("salesTax").value = "";
// Assign the value of a variable named salesTax
// to a text box
document.getElementById("salesTax").value =
salesTax.toFixed(2);
![Page 46: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/46.jpg)
One method of the Textbox object focus()
How to move the cursor to a text box document.getElementById("investment").focus();
![Page 47: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/47.jpg)
The relational operators ==
!=
<
<=
>
>=
![Page 48: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/48.jpg)
The syntax of the global isNaN method isNaN(expression)
Examples of the isNaN method isNaN("Harris")
// Returns true since "Harris" is not a number
isNaN("123.45")
// Returns false since "123.45"
// can be converted to a number
![Page 49: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/49.jpg)
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.
![Page 50: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/50.jpg)
Terms to know
conditional expression
relational operator
compound conditional expression
logical operator
One common programming error
Confusing the assignment operator ( = )
with the equality operator ( ==).
![Page 51: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/51.jpg)
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 + ".");
}
![Page 52: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/52.jpg)
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.");
}
![Page 53: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/53.jpg)
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);
}
}
![Page 54: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/54.jpg)
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
![Page 55: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/55.jpg)
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);
}
![Page 56: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/56.jpg)
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
![Page 57: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/57.jpg)
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");
![Page 58: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/58.jpg)
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");
![Page 59: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/59.jpg)
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
![Page 60: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/60.jpg)
Terms to know
function
return statement
call a function
return undefined
![Page 61: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/61.jpg)
Common events
Object Event
button onclick
window onload
![Page 62: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/62.jpg)
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>
![Page 63: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/63.jpg)
The web browser
after the Display Message button is clicked
![Page 64: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/64.jpg)
The Future Value application in a web browser
![Page 65: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/65.jpg)
The XHTML for the Future Value application <head>
<title>Future Value Calculator</title>
<link rel="stylesheet" type="text/css"
href="future_value.css" />
<script type="text/javascript"
src="future_value.js"></script>
</head>
![Page 66: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/66.jpg)
The XHTML (continued) <body>
<h1>Future Value Calculator</h1>
<p>Enter the values below and click "Calculate".</p>
<label for="investment">Monthly Investment:</label>
<input type="text" id="investment" /><br />
<label for="rate">Annual Interest Rate:</label>
<input type="text" id="rate" />%<br />
<label for="years">Number of Years:</label>
<input type="text" id="years" /><br />
<label for="futureValue">Future Value:</label>
<input type="text" id="futureValue"
disabled="disabled" /><br />
<label> </label>
<input type="button" id="calculate"
value="Calculate" /><br />
</body>
![Page 67: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/67.jpg)
The JavaScript for the Future Value application var $ = function (id) {
return document.getElementById(id);
}
window.onload = function () {
$("calculate").onclick = calculate_click;
$("investment").focus();
}
![Page 68: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/68.jpg)
The JavaScript (continued) var calculate_click = function () {
// Get the user entries from the first three text boxes.
var investment = parseFloat( $("investment").value );
var annualRate = parseFloat( $("rate").value );
var years = parseInt( $("years").value );
// Set the value of the fourth text box.
$("futureValue").value = "";
// Test the three input values for validity.
if (isNaN(investment) || investment <= 0) {
alert("Investment must be a valid number\nand
greater than zero.");
} else if(isNaN(annualRate) || annualRate <= 0) {
alert("Annual rate must be a valid number\nand
greater than zero.");
} else if(isNaN(years) || years <= 0) {
alert("Years must be a valid number\nand
greater than zero.");
![Page 69: a JavaScript application How to code - Gavilan Collegehhh.gavilan.edu/llam/LectureNotes/JavaScriptApp.pdf · Objectives (continued) x Describe the ways that number, string, Boolean,](https://reader031.vdocuments.us/reader031/viewer/2022030509/5ab8617e7f8b9aa6018c97af/html5/thumbnails/69.jpg)
The JavaScript (continued) // If all input values are valid, calculate future value.
} else {
var monthlyRate = annualRate / 12 / 100;
var months = years * 12;
var futureValue = 0;
for ( i = 1; i <= months; i++ ) {
futureValue = ( futureValue + investment ) *
(1 + monthlyRate);
}
// Set the value of the fourth text box to the future value
$("futureValue").value = futureValue.toFixed(2);
}
}