week 8
DESCRIPTION
Week 8TRANSCRIPT
![Page 1: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/1.jpg)
![Page 2: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/2.jpg)
Local –vs– Global Variables
Declaring variableswith var keyword makes them local
•They are available only within the function and hold no meaning outside of the function
Declaring variables without var keyword makes them global
•They are available outside the function and hold a meaning outside of the function
HEURISTIC:If it’s possible to define a variable as local, do it!
![Page 3: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/3.jpg)
Local –vs– Global Variables<script>
var a = 10;
display_a();
function display_a() {var a = 20;alert("Value of 'a' inside the function " +
a);}
alert("Value of 'a' outside the function " + a);</script>
Adapted from Global and Local variables in JavaScript Functions at webdevelopersnotes.com
![Page 4: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/4.jpg)
Local –vs– Global Variables
First Alert
Second Alert
![Page 5: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/5.jpg)
Local –vs– Global Variables<script>
var a = 10;
display_a();
function display_a() {a = 20;alert("Value of 'a' inside the function " +
a);}
alert("Value of 'a' outside the function " + a);</script>
Adapted from Global and Local variables in JavaScript Functions at webdevelopersnotes.com
![Page 6: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/6.jpg)
Local –vs– Global Variables
First Alert
Second Alert
![Page 7: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/7.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 7
Chapter 6
How to get input and display output
![Page 8: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/8.jpg)
More design by fiat“Do me a favor, I’d like a few more changes.”
![Page 9: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/9.jpg)
As a provider, I want to offer several compounding method so that I can sell more stuff
Future Value user story
Business Rule:
Compounding FrequencyMonthlyYearly
![Page 10: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/10.jpg)
As a provider, I want to offer a preset selection of investment amounts but also allow any amount so that I can sell more stuff
Future Value user story
Acceptance Critiera $1,000 $5,000$10,000
$25,000 Other
![Page 11: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/11.jpg)
As a user, I want to see my compounding results so that I can buy the right stuff
Future Value user story
Acceptance Criteria:
Monthly Compounded AmountYearly Compounded Amount
![Page 12: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/12.jpg)
What we start with
![Page 13: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/13.jpg)
Exercise #1
![Page 14: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/14.jpg)
future_value.html (body section) <section id="content"> <h1>Future Value Calculator</h1> <article id="data"> <fieldset> <legend>Select Frequency</legend> <p><input type="radio" name="calctype" id="monthly" value="monthly" checked />Monthly Compounding</p> <p><input type="radio" name="calctype" id="yearly" value="yearly" />Yearly Compounding</p> </fieldset> <p>Enter the values below and click "Calculate".</p>
![Page 15: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/15.jpg)
future_value.html (body section) <p>Enter the values below and click "Calculate".</p> <label for=”investment”>Investment Amount:</label> <input type="text" name="investment" id=”investment"/><br /> <label for="investment">One-Time Investment:</label> <select name="investment" id="investment"> <optgroup label=""> <option value="1000">$1,000</option> <option value="5000">$5,000</option> <option value="10000">$10,000</option> <option value="25000">$25,000</option> <option value="other">Other Amount</option> </optgroup> </select><br />
![Page 16: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/16.jpg)
future_value.html (body section) <div id="buttons"> <label> </label> <input type="button" id="calculate" value="Calculate" /><br /> </div> <p><input type="checkbox" name="display" id="display" value="display" checked /> Display both monthly and yearly results in the text area.</p> <p>Results</p> <textarea name="results" id="results" rows="4" cols="50"></textarea>
![Page 17: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/17.jpg)
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
![Page 18: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/18.jpg)
js/future_value.js
// Calculate future value with yearly interest
// Calculate future value with monthly interest
// Return output rounded to 2 decimal places
// Return all output rounded to 2 decimal places
// Auto load focus
![Page 19: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/19.jpg)
03/10/12 9:42 AM Slide 1
js/future_value.js } else { //calculate future value with yearly interest var futureValueYearly = $investment; for ( var $i = 1; $i <= $years; $i++ ) { futureValueYearly = ( futureValueYearly + futureValueYearly * $interest_rate * .01)); } // Calculate future value with monthly interest var futureValueMonthly = $investment; for ( var $i = 1; $i <= $years * 12; $i++ ) { futureValueMonthly = futureValueMonthly + ( futureValueMonthly * $interest_rate / 12 * .01); }
![Page 20: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/20.jpg)
03/07/12 9:43 AM Slide 1
js/future_value.js //return output rounded to 2 decimal places if ( document.getElementById("monthly").checked ) { document.getElementById("future_value").value = futureValueMonthly.toFixed(2); } else { document.getElementById("future_value").value = futureValueYearly.toFixed(2); }
![Page 21: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/21.jpg)
02/28/12 7:04 AM Slide 1
js/future_value.js // auto load focus window.onload = function () { document.getElementById("years").focus(); }
![Page 22: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/22.jpg)
Replace JavaScript Function with HTML5 attribute
// auto load focus window.onload = function () { document.getElementById("years").focus(); }
<label for="years">Number of Years:</label> <input type="text" id="years" autofocus><br />
![Page 23: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/23.jpg)
What we have so far
![Page 24: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/24.jpg)
Agenda • How to interact using Dialog boxes
• How to interact using Forms
• Common control methods and events
![Page 25: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/25.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 25
Syntax of the prompt method window.prompt( message, defaultValue );
Return values of the prompt method null // if the user clicks Cancel a string // if the user clicks OK
How to call the prompt method when expecting string data var username = prompt("Please enter your name:");
How to call the prompt method when expecting numerical data var age = parseInt( prompt("Please enter your age:", "18") ); var wage = parseFloat( prompt("Please enter the hourly wage", "5.35") );
![Page 26: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/26.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 26
A dialog box displayed by the prompt method
How to determine if the user clicked "Cancel" var age = prompt("Please enter your age:"); if ( age == null ) { alert("You clicked cancel."); }
![Page 27: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/27.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 27
Syntax of the confirm method window.confirm( message );
Return values of the confirm method true // if the user clicks OK false // if the user clicks Cancel
How to call the confirm method var response = confirm("Do you agree to the web site privacy policy?"); if (response == true) { alert("Thank you. You may continue to the web store."); }
![Page 28: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/28.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 28
A dialog box displayed by the confirm method
![Page 29: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/29.jpg)
Exercise #2
![Page 30: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/30.jpg)
03/07/12 10:13 AM Slide 1
js/future_value.js // Get user input from the first three text boxes. var $investment = parseFloat( document.getElementById("investment").value ); if ( isNaN($investment) ) {
$investment = parseFloat(prompt ("Enter investment amount:"));
}
![Page 31: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/31.jpg)
Agenda • How to interact using Dialog boxes
• How to interact using Forms
• Common control methods and events
![Page 32: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/32.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 32
Two properties of a Radio object object.checked object.value
XHTML code for two radio buttons <p>Accept or decline the web site privacy policy:</p> <p><input type="radio" name="policy" id="policy_accept" value="accept" />Accept</p> <p><input type="radio" name="policy" id="policy_decline" value="decline" />Decline</p>
The XHTML in a web browser
![Page 33: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/33.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 33
The $ function that gets an element by its ID var $ = function (id) { return document.getElementById(id); }
JavaScript code to process the radio buttons var status = "unknown"; if ( $("policy_accept").checked ) { status = $("policy_accept").value; } if ( $("policy_decline").checked ) { status = $("policy_decline").value; } if (status == "unknown") alert("You must accept or decline the privacy policy"); } else if (status == "accept") { alert("Thank you. You may continue to use the web store."); } else { alert("You cannot use the web store at this time."); }
![Page 34: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/34.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 34
HTML code for two radio buttons <p><input type="radio" name="policy" disabled id="policy_accept" value="accept" />Accept</p> <p><input type="radio" name="policy" disabled id="policy_decline" value="decline" checked="checked" />Decline</p> <p><input type="button" id="toggle" value="toggle" /></p>
The XHTML in a web browser
![Page 35: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/35.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 35
JavaScript code to set the radio button state var $ = function (id) { document.getElementById(id); } var toggleClick = function () { if ( $("policy_accept").checked ) { $("policy_decline").checked = true; } else { $("policy_accept").checked = true; } } window.onload = function () { $("toggle").onclick = toggleClick; }
![Page 36: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/36.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 36
Two properties of a Checkbox object object.checked object.value
XHTML code for a check box <p> <input type="checkbox" id="accept" /> I accept the web site privacy policy. </p>
The XHTML in a web browser
![Page 37: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/37.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 37
JavaScript code to process the check box var $ = function (id) { document.getElementById(id); } var accept = $("accept").checked; if ( accept ) { alert("Thank you. You may continue to the web store."); } else { alert("You cannot use the web store at this time.");
![Page 38: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/38.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 38
XHTML code for a check box <p><input type="checkbox" disabled="disabled" name="voteStatus" id="vote_status" /> You can vote when checked.</p>
The XHTML in a web browser
![Page 39: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/39.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 39
JavaScript code to set the state of the check box var $ = function (id) { document.getElementById(id); } $("vote_status").checked = false; var age = prompt("Please enter your age:"); if ( age == null ) { alert("You clicked cancel."); } else { age = parseInt(age); if ( age >= 18 ) { $("voteStatus").checked = true; } }
![Page 40: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/40.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 40
One property of a Select object object.value
XHTML code for a select list <p>Select your preferred contact method: <select id="contact"> <optgroup label="Method"> <option value="phone">Phone</option> <option value="email">E-Mail</option> <option value="txtmsg">Text Message</option> </optgroup> </select> </p>
The XHTML in a web browser
![Page 41: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/41.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 41
JavaScript code to process the list var $ = function (id) { document.getElementById(id); } var contact = $("contact").value; if ( contact == "phone" ) { alert("Preferred contact method: Phone"); } else if ( contact == "email" ) { alert("Preferred contact method: E-mail"); } else if ( contact == "txtmsg" ) { alert("Preferred contact method: Text Message"); } else { alert("Error selecting Preferred contact method."); }
![Page 42: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/42.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 42
One property of a Textarea object object.value
XHTML code for a text area <p><textarea name="comment" id="comment" rows="5" cols="40"></textarea></p>
The XHTML in a web browser
![Page 43: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/43.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 43
JavaScript code to process the text area var $ = function (id) { document.getElementById(id); }
var comment = $("comment").value; var charCount = comment.lenght; if ( comment == "" ) { alert("Please enter a comment."); } else { alert("Your Comment: " + charCount + “characters\n\n” + comment); }
Terms • hard return
• soft return
![Page 44: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/44.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 44
XHTML code for three checkboxes and a text area <p><input type="checkbox" name="privacy" id="privacy" /> Privacy Policy</p> <p><input type="checkbox" name="use" id="use" /> Acceptable Use Policy</p> <p><input type="checkbox" name="license" id="license" /> End User License Agreement</p> <textarea name="policies" id="policies" rows="6" cols="40"></textarea>
![Page 45: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/45.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 45
The XHTML in a web browser
![Page 46: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/46.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 46
JavaScript code for the text area var $ = function (id) { document.getElementById(id); } var updatePolicies = function () { var privacy = $("privacy").checked; var use = $("use").checked; var license = $("license").checked;
![Page 47: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/47.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 4703/13/12 7:02 AM Slide 1
JavaScript code for the text area (continued) var message; if ( privacy || use || license ) { message = "You agreed to these policies:\n\n"; if ( privacy ) { message += "- Privacy Policy\n"; } if ( use ) { message += "- Acceptable Use Policy\n"; } if ( license ) { message += "- End User License Agreement\n"; } } else { message = "You haven't agreed to any policies."; } $("policies").value = message; }
![Page 48: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/48.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 4803/07/12 12:17 PM Slide 1
JavaScript code for the text area (continued) window.onload = function () { $("privacy").onclick = updatePolicies; $("use").onclick = updatePolicies; $("license").onclick = updatePolicies; updatePolicies(); }
![Page 49: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/49.jpg)
Exercise #3
![Page 50: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/50.jpg)
03/10/12 7:46 AM Slide 1
js/future_value.js //return all output rounded to 2 decimal places to textbox if ( document.getElementById("display").checked ) { var textAreaMessage = "Future Value of $" + $investment + "\n\n"; textAreaMessage += "When compounded monthly: " + futureValueMonthly.toFixed(2) + "\n"; textAreaMessage += "When compounded yearly: futureValueYearly.toFixed(2); } else { textAreaMessage = ""; } document.getElementById("results").value = textAreaMessage; }
![Page 51: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/51.jpg)
Agenda • How to interact using Dialog boxes
• How to interact using Forms
• Common control methods and events
![Page 52: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/52.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 52
Common control methods object.focus() object.blur()
Common control events object.onfocus() object.onblur() object.onclick() object.ondblclick() object.onchange() object.onslect()
![Page 53: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/53.jpg)
![Page 54: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/54.jpg)
Event Handleras HTML Element Attribute
<input type=“text” id=“test” value=“test” eventHandler="JavaScript Function">
![Page 55: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/55.jpg)
Event Handler as JavaScript Object Property
document.getElementById(id).eventHandler
![Page 56: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/56.jpg)
Event handlersObject (HTML Element) Event Handlers
Selection list onBlur, onChange, onFocusText element onBlur, onChange, onFocus, onSelectTextarea element onBlur, onChange, onFocus, onSelectButton element onClickCheckbox onClickRadio button onClickReset button onClickSubmit button onClick
![Page 57: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/57.jpg)
Event Driven Programming Basics
1. Capture input via forms and dialog boxes using HTML and CSS
2. Identify what events that the app should respond to and their timing
3. Write a function for each event in JavaScript and connect to event handler in HTML
4. Generate output in HTML and CSS
![Page 58: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/58.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 58
The XHTML for a select list <select name="investment" id="investment"> <option value="1000">$1,000</option> <option value="5000">$5,000</option> <option value="10000">$10,000</option> <option value="25000">$25,000</option> </select><br />
The event handler for an onchange event var investmentChange = function () { calculateClick(); // Recalculate future value $("investment").blur(); // Remove the focus }
The event handler for an ondblclick event var yearsDblclick = function () { $("years").value = ""; // Clear textbox }
![Page 59: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/59.jpg)
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 59
Code that assigns event handlers to events window.onload = function () { $("calculate").onclick = calculateClick; $("investment").onchange = investmentChange; $("years").ondblclick = yearsDblclick; $("years").focus(); }
![Page 60: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/60.jpg)
Exercise #4
![Page 61: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/61.jpg)
02/28/12 7:08 AM Slide 1
js/future_value.js //auto recalc investment selection function investmentChange () { calculate_click(); document.getElementById("investment").blur(); } //clear years input when doubleclicked function yearsDoubleClick () { document.getElementById("years").value = ""; } // auto load focus
![Page 62: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/62.jpg)
future_value.html (body section) <label for="investment">One-Time Investment:</label> <select name="investment" id="investment" onChange="investmentChange()"> <optgroup label=""> <label for="years">Number of Years:</label> <input type="text" id="years" autofocus ondblclick="yearsDoubleClick()"/><br />
![Page 63: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/63.jpg)
Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 63
Chapter 7
How to work with numbers, strings,
and dates
![Page 64: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/64.jpg)
Even more design by fiat“It looks great. I’d like to add a few more things.
![Page 65: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/65.jpg)
As a user, I want to enter my email address so that Joey will add me to his mailing list
Future Value user story
Valid email address includes an @ sign and a period after the @ sign
Acceptance Criteria
![Page 66: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/66.jpg)
As a user, I want to see the date so that I can keep track of when I ran the calculation
Future Value user story
Date format = mm/dd/yyyyAcceptance Criteria
![Page 67: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/67.jpg)
Agenda • How to work with numbers
• How to work with Math object
• How to work with strings
• How to work with date and time
![Page 68: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/68.jpg)
Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 68
Properties of the Number object Number.MAX_VALUE Number.MIN_VALUE Number.POSITIVE_INFINITY Number.NEGATIVE_INFINITY Number.NaN
Shortcut numerical values Infinity -Infinity NaN
Testing for Infinity, -Infinity, and NaN if ( result == Infinity ) { alert( "The result exceeds " + Number.MAX_VALUE ); } else if ( result == -Infinity ) { alert( "The result is below -" + Number.MAX_VALUE ); } else if ( isNaN(result) ) { alert( "The result is not a number." ); }
![Page 69: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/69.jpg)
Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 69
Methods of the Number object object.toFixed(digits) object.toString(base) object.toExponential(digits) object.toPrecision(precision)
Using the toFixed method var subtotal = 19.99, rate = 0.075; var tax = subtotal * rate; // tax is 1.49925 tax = parseFloat( tax.toFixed(2) ); // tax is 1.5 alert ( tax.toFixed(2) ); // displays 1.50
Implicit use of the toString method var age = parseInt( prompt("Please enter your age.") ); alert( "Your age in decimal is " + age );
![Page 70: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/70.jpg)
Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 70
Syntax of the conditional operator ( conditional_expression ) ? value_if_true : value_if_false
Setting a string based on a comparison var message = ( age >= 18 ) ? "Can vote" : "Cannot vote";
Selecting a singular or plural ending var ending = ( error_count == 1 ) ? "" : "s". var message = "Found " + error_count + " error" + ending;
Returning a value based on a comparison return ( number > highest ) ? highest : number;
![Page 71: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/71.jpg)
Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 71
Bounding a value within a fixed range value = ( value > max ) ? max : ( ( value < min ) ? min : value );
Bounding a value within a fixed range (rewritten) if ( value > max ) { value = max; } else if ( value < min ) { value = min; }
![Page 72: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/72.jpg)
Agenda • How to work with numbers
• How to work with Math object
• How to work with strings
• How to work with date and time
![Page 73: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/73.jpg)
Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 73
Basic escape sequences \t // Tab \n // New line \" // Double quote \' // Single quote \\ // Backslash
Examples of the basic escape sequences var quote = "He said \"Goodbye.\""; var message = "Error\t123\nText\tInvalid Operation"; var info = "The file is in C:\\murach";
![Page 74: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/74.jpg)
Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 74
One property of String objects object.length
Displaying the length of a string var message_1 = "JavaScript"; var result_1 = message_1.length; // result_1 is 10
![Page 75: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/75.jpg)
Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 75
Methods of String objects object.charAt(position) object.concat(string1, string2, ...) object.indexOf(search, position) object.substring(start, end) object.toLowerCase() object.toUpperCase()
![Page 76: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/76.jpg)
Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 76
The charAt method var message_2 = "JavaScript"; var letter = message_2.charAt(4); // letter is "S"
The concat method var message_3 = "Java"; var result_3 = message_3.concat("Script"); // "JavaScript"
The indexOf method var result_4a = message_2.indexOf("a"); // result_4a is 1 var result_4b = message_2.indexOf("a",2); // result_4b is 3 var result_4c = message_2.indexOf("s"); // result_4c is -1
The substring method var result_5a = message_2.substring(4); // "Script" var result_5b = message_2.substring(0,4); // "Java"
The toLowerCase and toUpperCase methods var result_6a = message_2.toLowerCase(); // "javascript" var result_6b = message_2.toUpperCase(); // "JAVASCRIPT"
![Page 77: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/77.jpg)
Exercise #5
![Page 78: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/78.jpg)
future_value.html (body section) <p>Results</p> <textarea name="results" id="results" rows="4" cols="50"></textarea> <!-- validate email address--> <hr /> <label for="email">Email Address:</label> <input type="text" id="email" /><br /> <label> </label> <input type="button" id="processEmail" value="Process" onclick="email_click()"/><br />
![Page 79: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/79.jpg)
What we did
![Page 80: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/80.jpg)
03/07/12 12:42 PM Slide 1
js/future_value.js //validate email address function email_click () { var emailAddress = document.getElementById("email").value; var atLocation = emailAddress.indexOf("@"); if (atLocation == -1) {
alert ("A valid email address must include an @ sign.");
} else
var dotLocation = emailAddress.indexOf(".",atLocation); if (dotLocation == -1) { alert ("A valid email address must include a period after the @ sign."); } if (atLocation > 0 && dotLocation > 0) { var domainName = emailAddress.substring(atLocation + 1); alert ("The domain name is " + domainName) } }
![Page 81: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/81.jpg)
Agenda • How to work with numbers
• How to work with Math object
• How to work with strings
• How to work with date and time
![Page 82: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/82.jpg)
Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 82
How to get the current date and time var now = new Date();
How to create a Date object from a date string var election_day = new Date("11/8/2008"); var grand_opening = new Date("2/16/2009 8:00"); var departure_time = new Date("4/6/2009 18:30:00");
Syntax for creating a Date object by parts new Date( year, month, day, hours, minutes, seconds, milliseconds)
Examples of creating a Date object by parts var election_day = new Date(2008, 10, 4); // 10 is Nov var grand_opening = new Date(2009, 1, 16, 8); // 1 is Feb var depart_time = new Date(2009, 3, 6, 18, 30); // 3 is Apr
How to copy another date object var check_out = new Date("11/8/2008"); var due_date = new Date( check_out );
![Page 83: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/83.jpg)
Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 83
The formatting methods of a Date object object.toString() object.toDateString() object.toTimeString()
Examples of the formatting methods var birthday = new Date( 2005, 0, 4, 8, 25); birthday.toString() // "Tue Jan 04 2005 08:25:00 GMT-0500" birthday.toDateString() // "Tue Jan 04 2005" birthday.toTimeString() // "08:25:00 GMT-0500"
![Page 84: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/84.jpg)
Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 84
The get and set methods of a Date object object.getTime() object.getFullYear() object.getMonth() object.getDate() object.getHours() object.getMinutes() object.getSeconds() object.getMilliseconds() object.setFullYear(year) object.setMonth(month) object.setDate(day) object.setHours(hour) object.setMinutes(minute) object.setSeconds(second) object.setMilliseconds(ms)
![Page 85: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/85.jpg)
Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 85
Display the date in your own format var depart_time = new Date(2009, 3, 6, 18, 30); var year = depart_time.getFullYear(); var month = depart_time.getMonth() + 1; // Add 1 for month var date = depart_time.getDate(); var dateText = year + "-"; dateText += ((month < 10) ? "0" + month : month) + "-"; dateText += (date < 10) ? "0" + date : date; // Final dateText is "2009-04-06"
![Page 86: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/86.jpg)
Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 86
Display the time in your own format var depart_time = new Date(2009, 3, 6, 18, 30); var hours = depart_time.getHours(); var minutes = depart_time.getMinutes(); var seconds = depart_time.getSeconds(); var timeText = (hours % 12 == 0) ? 12 : hours % 12; timeText += ":"; timeText += ( minutes < 10 ) ? "0" + minutes : minutes; timeText += ":"; timeText += ( seconds < 10 ) ? "0" + seconds : seconds; timeText += ( hours < 12 ) ? " am" : " pm"; // Final timeText is "6:30:00 pm"
![Page 87: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/87.jpg)
Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 87
Calculate the days until the New Year var now = new Date(); // Get the current time var new_year = new Date(now); // Copy the current time new_year.setMonth(0); // Set the month to January new_year.setDate(1); // Set the day to the 1st // Add 1 to the year new_year.setFullYear( new_year.getFullYear() + 1 ); // Get ms to the New Year var time_left = new_year.getTime() - now.getTime(); // Convert ms to days var days_left = Math.ceil( time_left / 86400000);
![Page 88: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/88.jpg)
Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 88
How to calculate a due date var check_out = new Date() var due_date = new Date( check_out ); // Set the days to 3 weeks later due_date.setDate( due_date.getDate() + 21 );
How to find the end of the month var end_of_month = new Date(); // Set the month to next month end_of_month.setMonth( end_of_month.getMonth() + 1 ); // Set the date to one day before the start of the month end_of_month.setDate( 0 );
![Page 89: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/89.jpg)
Exercise #6
![Page 90: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/90.jpg)
future_value.html (body section) <p>Results</p> <textarea name="results" id="results" rows="4" cols="50"></textarea> <!-- today's date--> <p> <script>getToday (); </script> <noscript>You must enable JavaScript for this application.</noscript> </p> <!-- validate email address-->
![Page 91: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/91.jpg)
03/07/12 12:50 PM Slide 1
js/future_value.js //date function function getToday () { var currentDate = new Date(); var month = currentDate.getMonth() + 1; var month = (month < 10) ? "0" + month : month; var day = currentDate.getDate(); var day = (day < 10) ? "0" + day : day; var year = currentDate.getFullYear(); var dateString = "Today is " + month + "/" + day + "/" + year ; document.writeln(dateString); }
![Page 92: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/92.jpg)
All done!
![Page 93: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/93.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 93
Chapter 8
How to code control statements
![Page 94: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/94.jpg)
Another gig“Way to go team. You did so well that I want you to fix the product discount app using JavaScript. Do me a favor, title the app invoice total calculator and make the background orange”
![Page 95: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/95.jpg)
Invoice business rules
Retail customers
$0 < $100 = 0%
$100 < $250 = 10%
> $250 = 25%
Business Rule #1
![Page 96: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/96.jpg)
Invoice business rules
Commerical customers
$0 < $250 = 20%
> $250 = 30%
Business Rule #2
![Page 97: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/97.jpg)
Your starting point
![Page 98: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/98.jpg)
Murach's PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 98
Chapter 1
Introduction to web development
and PHP
![Page 99: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/99.jpg)
Murach's PHP and MySQL, C1 © 2010, Mike Murach & Associates, Inc. Slide 99
The first page of an application (index.html)
![Page 100: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/100.jpg)
Murach's PHP and MySQL, C1 © 2010, Mike Murach & Associates, Inc. Slide 100
The second page (display_discount.php)
![Page 101: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/101.jpg)
From index.php to invoice_total.hmtl (body section) <section id="content"> <h1>Product Discount Calculator</h1> <form action="display_discount.php" method="post"> <article id="data"> <label>Product Description:</label> <input type="text" name="product_description" id=”product_description"/><br /> <label>List Price:</label> <input type="text" name="list_price" id=”list_price”/><br /> <label for="type">Customer Type:</label> <select name="type" id="type"> <option value="R">Retail</option> <option value="C">Commercial</option> </select><br /> <label>Discount Percent:</label> <input type="text" name="discount_percent" id="discount_percent" disabled />%<br /> </article>
![Page 102: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/102.jpg)
From index.php to invoice_total.html (body section) <label>Discount Percent:</label> <input type="text" name="discount_percent" id="discount_percent" disabled />%<br /> <label for="discount">Discount Amount:</label> <input type="text" name="discount" id="discount" disabled /><br /> <label for="total">Invoice Total:</label> <input type="text" name="total" id="total" disabled /><br /> </article> <div id="buttons"> <label> </label> <input type="submit" value="Calculate Discount" onclick = "calculate_click()"/><br /> </div> </form> </section>
![Page 103: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/103.jpg)
What we have so far
![Page 104: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/104.jpg)
Behavior from display_discount.php // get the data from the form $product_description = $_POST['product_description']; $list_price = $_POST['list_price']; $discount_percent = $_POST['discount_percent']; // calculate the discount $discount = $list_price * $discount_percent * .01; $discount_price = $list_price - $discount;
![Page 105: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/105.jpg)
03/10/12 6:53 AM Slide 1
js/invoice_total.js //main function that calculates the price //user enters list price //user selects customer type //determine and return discount percent //calculate and return discount amount //calculate and return invoice amount
//auto load script
![Page 106: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/106.jpg)
02/29/12 6:30 PM Slide 1
js/invoice_total.js //main function that caluculates the price
function calculate_click () {
//calculate and return invoice amount
}
//auto load script
![Page 107: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/107.jpg)
02/29/12 5:45 PM Slide 1
js/invoice_total.js //user enters list price var invoiceSubtotal = parseFloat (document.getElementById("list_price").value ); document.getElementById("list_price").value = invoiceSubtotal.toFixed(2); //user selects customer type var customerType = document.getElementById("type").value;
![Page 108: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/108.jpg)
02/29/12 6:31 PM Slide 1
js/invoice_total.js //calculate and return discount amount var discountAmount = invoiceSubtotal * discountPercent; document.getElementById("discount").value discountAmount.toFixed(2);
//calculate and return invoice amount
var invoiceTotal = invoiceSubtotal –discountAmount;document.getElementById("total").value = invoiceTotal.toFixed(2);
![Page 109: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/109.jpg)
03/10/12 6:55 AM Slide 1
js/invoice_total.js //auto loads script
window.onload = function () {
document.getElementById("product_description").focus();
![Page 110: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/110.jpg)
Replace JavaScript Function with HTML5 attribute
// auto load focus window.onload = function () { document.getElementById("product_description").focus(); }
<label for="product_description">Product Description:</label> <input type="text" name="product_description" id=”product_description" autofocus><br />
![Page 111: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/111.jpg)
Agenda • How to code conditional expressions
• How to code selection structures
• How to code iteration structures
![Page 112: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/112.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 112
The equality operators
Operator Description
== Equal
!= Not equal
The identity operators
Operator Description
=== Equal
!== Not equal
Description • The equality operators perform type coercion.
• The identity operators do not perform type coercion.
![Page 113: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/113.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 113
The relational operators
Operator Description
< Less than
<= Less than or equal
> Greater than
>= Greater than or equal
Comparing strings to numbers
Expression Result
1 < "3" true
"10" < 3 false
![Page 114: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/114.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 114
Comparing strings to strings
Expression Result
"apple" < "orange" true
"apple" < "appletree" true
"Orange" < "apple" true
"@" < "$" false
![Page 115: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/115.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 115
The logical operators
Operator Name
! NOT
&& AND
|| OR
The NOT operator !isNaN(number)
The AND operator age >= 18 && score >= 680
The OR operator state == "CA" || state == "NC"
![Page 116: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/116.jpg)
JavaScript operator taxonomy
Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 116
Classification OperatorUnary ++, --, -, !
Binary +, -, /, *, <, >, %, =<, >=, +=, -=, /=, *=, %=, &&, ||, ==, !=, ===, !==,
Ternary ?
![Page 117: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/117.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 117
The order of precedence
Order Operators
1 !
2 <, <=, >, >=
3 ==, !=, ===, !==
4 &&
5 ||
AND, OR, and NOT operators !oldCustomer || loanAmount >= 10000 && score < minScore + 200
How parentheses can change the evaluation (!oldCustomer || loanAmount >= 10000) && score < minScore + 200
![Page 118: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/118.jpg)
Agenda • How to code conditional expressions
• How to code selection structures
• How to code iteration structures
![Page 119: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/119.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 119
An if clause with one statement and no braces if ( rate === undefined ) rate = 0.075;
An if clause with one statement and braces if ( qualified ) { alert("You qualify for enrollment."); }
![Page 120: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/120.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 120
If and else clauses with no braces if ( age >= 18 ) alert("You may vote."); else alert("You may not vote.");
Why you should use braces if ( age >= 18 ) alert("You may vote."); else alert("You may not vote."); may_vote = false; // Not a part of the else clause.
Braces make your code easier to modify if ( score >= 680 ) { alert("Your loan is approved."); } else { alert("Your loan is not approved."); }
![Page 121: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/121.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 121
A nested if statement var isLeapYear; if ( year % 4 == 0 ) { if ( year % 100 == 0 ) { if ( year % 400 == 0) { isLeapYear = true; // div by 4, 100, and 400 } else { isLeapYear = false; // div by 4 & 100, not 400 } } else { isLeapYear = true; // div by 4, not 100 } } else { isLeapYear = false; // no div by 4 }
![Page 122: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/122.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 122
An if statement with one else if clause if ( age < 18 ) { alert("You're too young for a loan."); } else if ( score < 680 ) { alert("Your credit score is too low for a loan."); }
An if statement with an else if and an else clause if ( age < 18 ) { alert("You're too young for a loan."); } else if ( score < 680 ) { alert("Your credit score is too low for a loan."); } else { alert("You're approved for your loan."); }
![Page 123: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/123.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 123
An if statement with else if clauses and else clauses rateIsValid = false; if ( isNaN(rate) ) { alert("Rate is not a number."); } else if (rate < 0) { alert("Rate cannot be less than zero."); } else if (rate > 0.2) { alert("Rate cannot be greater than 20%."); } else { rateIsValid = true; }
![Page 124: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/124.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 124
An if statement to determine a student’s letter grade if ( average >= 89.5 ) { grade = "A"; } else if ( average >= 79.5 ) { grade = "B"; } else if ( average >= 69.5 ) { grade = "C"; } else if ( average >= 64.5 ) { grade = "D"; } else { grade = "F"; }
![Page 125: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/125.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 125
A switch statement with a default case switch ( letterGrade ) { case "A": message = "well above average"; break; case "B": message = "above average"; break; case "C": message = "average"; break; case "D": message = "below average"; break; case "F": message = "failing"; break; default: message = "invalid grade"; break; }
![Page 126: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/126.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 126
A switch statement with fall through switch ( letterGrade ) { case "A": case "B": message = "Scholarship approved."; break; case "C": message = "Application requires review."; break; case "D": case "F": message = "Scholarship not approved."; break; }
![Page 127: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/127.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 127
The if statement for a Future Value application // Test if input is valid if (isNaN(investment) || investment <= 0) { alert("Investment is not a valid number."); } else if(isNaN(annualRate) || annualRate <= 0) { alert("Annual rate is not a valid number."); } else if(isNaN(years) || years <= 0) { alert("Years is not a valid number."); // If input is valid, calculate future value } else { // code that calculates the future value goes here }
![Page 128: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/128.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 128
How to use a flag to get the same results // Test if input is valid var valid = true; if (isNaN(investment) || investment <= 0) { alert("Investment is not a valid number."); valid = false; } else if(isNaN(annualRate) || annualRate <= 0) { alert("Annual rate is not a valid number."); valid = false; } else if(isNaN(years) || years <= 0) { alert("Years is not a valid number."); valid = false; } // If input is valid, calculate the future value if ( valid ){ // code that calculates the future value goes here }
![Page 129: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/129.jpg)
Agenda • How to code conditional expressions
• How to code selection structures
• How to code iteration structures
![Page 130: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/130.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 130
A while loop to validate user input var value = parseInt( prompt("Please enter a number from 1 to 10") ); while ( isNaN(value) || value < 1 || value > 10 ) { alert("You did not enter a number between 1 and 10."); value = parseInt( prompt("Please enter a number from 1 to 10") ); }
![Page 131: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/131.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 131
A while loop that finds the average of a series of numbers alert("Enter a non-number to stop."); var total = 0, count = 0, number; number = parseFloat( prompt("Enter a number") ); while ( !isNaN(number) ) { total += number; count++; number = parseFloat( prompt("Enter another number") ); } var average = total / count; if ( isNaN(average) ) { alert("You didn't enter any numbers."); } else { alert("The average is: " + average); }
![Page 132: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/132.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 132
A while loop that counts dice rolls until a six is rolled var rolls = 1; while ( random_number(1,6) != 6 ) { rolls++; } alert("Number of times to roll a six: " + rolls); // NOTE: See figure 7-5 for the random_number function
![Page 133: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/133.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 133
Nested while loops that find the average and max to roll a six var total = 0, count = 0, max = -Infinity; var rolls; while ( count < 10000 ) { rolls = 1; while ( random_number(1, 6) != 6 ) { rolls++; } total += rolls; count++; if ( rolls > max ) max = rolls; } var average = total / count; alert ("Average rolls: " + average); alert ("Max rolls: " + max);
![Page 134: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/134.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 134
A do-while loop to validate user input var value, valid; do { value = parseInt( prompt("Enter a number between 1 and 10") ); if (isNaN(value) || value < 1 || value > 10) { alert("You did not enter a valid number."); valid = false; } else { valid = true; } } while ( !valid );
![Page 135: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/135.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 135
A do-while loop that counts dice rolls until a six is rolled var rolls = 0; do { rolls ++; } while ( random_number(1,6) != 6 ); alert("Number of times to roll a six: " + rolls); // NOTE: See figure 7-5 for the random_number function
![Page 136: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/136.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 136
A do-while loop that finds max and min values alert("Enter a non-number to stop."); var max = -Infinity, min = Infinity, number; var value_entered = false, stop = false; do { number = parseFloat( prompt("Enter a number") ); if ( isNaN(number) ) { stop = true; } else { value_entered = true; if ( number > max ) max = number; if ( number < min ) min = number; } } while ( !stop ); if (value_entered) { alert("Max: " + max + ", Min: " + min); } else { alert("No numbers entered."); }
![Page 137: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/137.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 137
A for statement for ( var count = 1; count <= 10; count++ ) { alert ( count ); }
A while statement that does the same thing var count = 1; while ( count <= 10 ) { alert ( count ); count++; }
![Page 138: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/138.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 138
A for loop to display even numbers from 2 to 10 for ( var number = 2; number <= 10; number += 2 ) { alert( number ); }
A for loop to reverse a string var message = "JavaScript", reverse = ""; for (var i = message.length - 1; i >= 0; i-- ) { reverse += message.charAt(i); } alert(reverse); // Displays "tpircSavaJ"
A for loop to display all the factors of a number var number = 18; for ( var i = 1; i < number; i++ ) { if ( number % i == 0 ) { alert( i + " is a factor of " + number ); } }
![Page 139: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/139.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 139
A for loop to determine if a number is prime var number = 31, prime = true; for ( var i = 2; i < number; i++ ) { if ( number % i == 0 ) prime = false; } if (prime) { alert( number + " is prime."); } else { alert( number + " is not prime."); }
![Page 140: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/140.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 140
The break statement in a while loop var number; while (true) { number = parseInt( prompt("Enter a number from 1 to 10.") ); if ( isNaN(number) || number < 1 || number > 10 ) { alert("Invalid entry. Try again."); } else { break; } }
The break statement in a for loop var number = 31, prime = true; for ( var i = 2; i < number; i++ ) { if ( number % i == 0 ) { prime = false; break; } }
![Page 141: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/141.jpg)
Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 141
The continue statement in a for loop for ( var number = 1; number <= 10; number++ ) { if ( number % 3 == 0 ) continue; alert(number); } // Only displays 1, 2, 4, 5, 7, 8, and 10
The continue statement in a while loop var number = 1; while ( number <= 10 ) { if ( number % 3 == 0 ) { number++; continue; } alert(number); number++; } // Only displays 1, 2, 4, 5, 7, 8, and 10
![Page 142: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/142.jpg)
Exercise #6
![Page 143: Week 8](https://reader034.vdocument.in/reader034/viewer/2022042816/559aa3cc1a28abc4508b465a/html5/thumbnails/143.jpg)
03/10/12 11:18 AM Slide 1
js/invoice_total.js ; //determine and return discount percent switch ( customerType ) { case "R": if (invoiceSubtotal < 100) discountPercent = .0; else if (invoiceSubtotal >= 100 && invoiceSubtotal < 250) discountPercent = .1; else if (invoiceSubtotal >= 250) discountPercent = .25; break; case "C": if (invoiceSubtotal < 250) discountPercent = .2; else if (invoiceSubtotal >= 250) discountPercent = .3; break; }