Week 8

830 views
730 views

Published on

Week 8

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

  • Be the first to like this

No Downloads
Views
Total views
830
On SlideShare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
5
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Week 8

  1. 1. Local –vs– Global VariablesDeclaring variables Declaring variableswith var keyword makes without var keywordthem local makes them global•They are available only •They are availablewithin the function and outside the function andhold no meaning outside hold a meaning outside ofof the function the function HEURISTIC: If it’s possible to define a variable as local, do it!
  2. 2. 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
  3. 3. Local –vs– Global Variables First AlertSecond Alert
  4. 4. 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
  5. 5. Local –vs– Global Variables First AlertSecond Alert
  6. 6. Chapter 6 How to get input and display outputMurach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 7
  7. 7. More design by fiat“Do me a favor, I’d like a fewmore changes.”
  8. 8. Future Value user storyAs a provider, I want to offer severalcompounding method so that I can sell morestuffBusiness Rule: Compounding Frequency Monthly Yearly
  9. 9. Future Value user storyAs a provider, I want to offer a presetselection of investment amounts but alsoallow any amount so that I can sell morestuff Acceptance Critiera $1,000 $5,000 $10,000 $25,000 Other
  10. 10. Future Value user storyAs a user, I want to see my compoundingresults so that I can buy the right stuffAcceptance Criteria: Monthly Compounded Amount Yearly Compounded Amount
  11. 11. What we start with
  12. 12. Exercise #1
  13. 13. 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>
  14. 14. 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 />
  15. 15. future_value.html (body section)<div id="buttons"> <label>&nbsp;</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>
  16. 16. 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
  17. 17. 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
  18. 18. js/future_value.js} else {//calculate future value with yearly interestvar futureValueYearly = $investment;for ( var $i = 1; $i <= $years; $i++ ) { futureValueYearly = ( futureValueYearly + futureValueYearly * $interest_rate * .01)); }// Calculate future value with monthly interestvar futureValueMonthly = $investment;for ( var $i = 1; $i <= $years * 12; $i++ ) { futureValueMonthly = futureValueMonthly + ( futureValueMonthly * $interest_rate / 12 * .01); }03/10/12 9:42 AM Slide 1
  19. 19. js/future_value.js//return output rounded to 2 decimal placesif ( document.getElementById("monthly").checked ) { document.getElementById("future_value").value = futureValueMonthly.toFixed(2);} else { document.getElementById("future_value").value = futureValueYearly.toFixed(2);}03/07/12 9:43 AM Slide 1
  20. 20. js/future_value.js// auto load focuswindow.onload = function () { document.getElementById("years").focus();}02/28/12 7:04 AM Slide 1
  21. 21. Replace JavaScript Function with HTML5 attribute// auto load focuswindow.onload = function () { document.getElementById("years").focus();}<label for="years">Number of Years:</label><input type="text" id="years" autofocus><br />
  22. 22. What we have so far
  23. 23. Agenda• How to interact using Dialog boxes• How to interact using Forms• Common control methods and events
  24. 24. 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") );Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 25
  25. 25. 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."); }Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 26
  26. 26. 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."); }Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 27
  27. 27. A dialog box displayed by the confirm methodMurach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 28
  28. 28. Exercise #2
  29. 29. 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:")); }03/07/12 10:13 AM Slide 1
  30. 30. Agenda• How to interact using Dialog boxes• How to interact using Forms• Common control methods and events
  31. 31. 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 browserMurach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 32
  32. 32. 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."); }Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 33
  33. 33. 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 browserMurach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 34
  34. 34. 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; }Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 35
  35. 35. 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 browserMurach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 36
  36. 36. 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.");Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 37
  37. 37. 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 browserMurach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 38
  38. 38. 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; } }Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 39
  39. 39. 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 browserMurach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 40
  40. 40. 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."); }Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 41
  41. 41. 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 browserMurach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 42
  42. 42. 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 + “charactersnn” + comment); } Terms • hard return • soft returnMurach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 43
  43. 43. 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>Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 44
  44. 44. The XHTML in a web browserMurach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 45
  45. 45. JavaScript code for the text areavar $ = function (id) { document.getElementById(id);}var updatePolicies = function () { var privacy = $("privacy").checked; var use = $("use").checked; var license = $("license").checked;Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 46
  46. 46. JavaScript code for the text area (continued)var message; if ( privacy || use || license ) { message = "You agreed to these policies:nn"; if ( privacy ) { message += "- Privacy Policyn"; } if ( use ) { message += "- Acceptable Use Policyn"; } if ( license ) { message += "- End User License Agreementn"; } } else { message = "You havent agreed to any policies."; } $("policies").value = message;}03/13/12 JavaScript, C6Murach’s 7:02 AM © 2009, Mike Murach & Associates, Inc. Slide 1 47 Slide
  47. 47. JavaScript code for the text area (continued)window.onload = function () { $("privacy").onclick = updatePolicies; $("use").onclick = updatePolicies; $("license").onclick = updatePolicies; updatePolicies();} Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 4803/07/12 12:17 PM Slide 1
  48. 48. Exercise #3
  49. 49. 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 + "nn"; textAreaMessage += "When compounded monthly: " + futureValueMonthly.toFixed(2) + "n"; textAreaMessage += "When compounded yearly: futureValueYearly.toFixed(2); } else { textAreaMessage = ""; } document.getElementById("results").value = textAreaMessage;}
  50. 50. Agenda• How to interact using Dialog boxes• How to interact using Forms• Common control methods and events
  51. 51. Common control methods object.focus() object.blur() Common control events object.onfocus() object.onblur() object.onclick() object.ondblclick() object.onchange() object.onslect()Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 52
  52. 52. Event Handler as HTML Element Attribute<input type=“text” id=“test” value=“test” eventHandler="JavaScript Function">
  53. 53. Event Handler as JavaScript Object Propertydocument.getElementById(id).eventHandler
  54. 54. Event handlers Object (HTML Element) Event HandlersSelection list onBlur, onChange, onFocusText element onBlur, onChange, onFocus, onSelectTextarea element onBlur, onChange, onFocus, onSelectButton element onClickCheckbox onClickRadio button onClickReset button onClickSubmit button onClick
  55. 55. Event Driven Programming Basics1. Capture input via forms and dialog boxes using HTML and CSS2. Identify what events that the app should respond to and their timing3. Write a function for each event in JavaScript and connect to event handler in HTML4. Generate output in HTML and CSS
  56. 56. 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 }Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 58
  57. 57. Code that assigns event handlers to events window.onload = function () { $("calculate").onclick = calculateClick; $("investment").onchange = investmentChange; $("years").ondblclick = yearsDblclick; $("years").focus(); }Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 59
  58. 58. Exercise #4
  59. 59. js/future_value.js//auto recalc investment selectionfunction investmentChange () { calculate_click(); document.getElementById("investment").blur();}//clear years input when doubleclickedfunction yearsDoubleClick () { document.getElementById("years").value = "";}// auto load focus02/28/12 7:08 AM Slide 1
  60. 60. 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 />
  61. 61. Chapter 7 How to work with numbers, strings, and datesMurach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 63
  62. 62. Even more design by fiat“It looks great. I’d like to add afew more things.
  63. 63. Future Value user storyAs a user, I want to enter my emailaddress so that Joey will add me to hismailing listAcceptance Criteria Valid email address includes an @ sign and a period after the @ sign
  64. 64. Future Value user storyAs a user, I want to see the date so that Ican keep track of when I ran thecalculationAcceptance Criteria Date format = mm/dd/yyyy
  65. 65. Agenda• How to work with numbers• How to work with Math object• How to work with strings• How to work with date and time
  66. 66. 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." ); }Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 68
  67. 67. 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 );Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 69
  68. 68. 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;Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 70
  69. 69. 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; }Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 71
  70. 70. Agenda• How to work with numbers• How to work with Math object• How to work with strings• How to work with date and time
  71. 71. 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 = "Errort123nTexttInvalid Operation"; var info = "The file is in C:murach";Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 73
  72. 72. 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 10Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 74
  73. 73. Methods of String objects object.charAt(position) object.concat(string1, string2, ...) object.indexOf(search, position) object.substring(start, end) object.toLowerCase() object.toUpperCase()Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 75
  74. 74. 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"Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 76
  75. 75. Exercise #5
  76. 76. 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>&nbsp;</label><input type="button" id="processEmail" value="Process" onclick="email_click()"/><br />
  77. 77. What we did
  78. 78. js/future_value.js//validate email addressfunction 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) }}03/07/12 12:42 PM Slide 1
  79. 79. Agenda• How to work with numbers• How to work with Math object• How to work with strings• How to work with date and time
  80. 80. 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 );Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 82
  81. 81. 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"Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 83
  82. 82. 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)Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 84
  83. 83. 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"Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 85
  84. 84. 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"Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 86
  85. 85. 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);Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 87
  86. 86. 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 );Murach’s JavaScript, C7 © 2009, Mike Murach & Associates, Inc. Slide 88
  87. 87. Exercise #6
  88. 88. future_value.html (body section)<p>Results</p><textarea name="results" id="results" rows="4" cols="50"></textarea><!-- todays date--><p> <script>getToday (); </script> <noscript>You must enable JavaScript for this application.</noscript></p><!-- validate email address-->
  89. 89. js/future_value.js//date functionfunction 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);}03/07/12 12:50 PM Slide 1
  90. 90. All done!
  91. 91. Chapter 8 How to code control statementsMurach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 93
  92. 92. Another gig“Way to go team. You did sowell that I want you to fix theproduct discount app usingJavaScript. Do me a favor, titlethe app invoice total calculatorand make the backgroundorange”
  93. 93. Invoice business rulesBusiness Rule #1 Retail customers $0 < $100 = 0% $100 < $250 = 10% > $250 = 25%
  94. 94. Invoice business rulesBusiness Rule #2 Commerical customers $0 < $250 = 20% > $250 = 30%
  95. 95. Your starting point
  96. 96. Chapter 1 Introduction to web development and PHPMurachs PHP and MySQL, C2 © 2010, Mike Murach & Associates, Inc. Slide 98
  97. 97. The first page of an application (index.html)Murachs PHP and MySQL, C1 © 2010, Mike Murach & Associates, Inc. Slide 99
  98. 98. The second page (display_discount.php)Murachs PHP and MySQL, C1 © 2010, Mike Murach & Associates, Inc. Slide 100
  99. 99. 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>
  100. 100. 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>&nbsp;</label> <input type="submit" value="Calculate Discount" onclick = "calculate_click()"/><br /> </div> </form> </section>
  101. 101. What we have so far
  102. 102. 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;
  103. 103. 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 script03/10/12 6:53 AM Slide 1
  104. 104. js/invoice_total.js//main function that caluculates the pricefunction calculate_click () { //calculate and return invoice amount}//auto load script02/29/12 6:30 PM Slide 1
  105. 105. js/invoice_total.js//user enters list pricevar invoiceSubtotal = parseFloat (document.getElementById("list_price").value );document.getElementById("list_price").value = invoiceSubtotal.toFixed(2);//user selects customer typevar customerType = document.getElementById("type").value;02/29/12 5:45 PM Slide 1
  106. 106. js/invoice_total.js//calculate and return discount amountvar discountAmount = invoiceSubtotal * discountPercent;document.getElementById("discount").value discountAmount.toFixed(2);//calculate and return invoice amountvar invoiceTotal = invoiceSubtotal –discountAmount;document.getElementById("total").value = invoiceTotal.toFixed(2);02/29/12 6:31 PM Slide 1
  107. 107. js/invoice_total.js//auto loads scriptwindow.onload = function () { document.getElementById("product_description").focus();
  108. 108. Replace JavaScript Function with HTML5 attribute// auto load focuswindow.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 />
  109. 109. Agenda• How to code conditional expressions• How to code selection structures• How to code iteration structures
  110. 110. 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.Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 112
  111. 111. 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 falseMurach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 113
  112. 112. Comparing strings to strings Expression Result "apple" < "orange" true "apple" < "appletree" true "Orange" < "apple" true "@" < "$" falseMurach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 114
  113. 113. 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"Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 115
  114. 114. JavaScript operator taxonomy Classification Operator Unary ++, --, -, ! Binary +, -, /, *, <, >, %, =<, >=, +=, -=, /=, *=, %=, &&, ||, ==, !=, ===, !==, Ternary ?Murach’s JavaScript, C6 © 2009, Mike Murach & Associates, Inc. Slide 116
  115. 115. 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 + 200Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 117
  116. 116. Agenda• How to code conditional expressions• How to code selection structures• How to code iteration structures
  117. 117. 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."); }Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 119
  118. 118. 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."); }Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 120
  119. 119. 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 }Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 121
  120. 120. An if statement with one else if clause if ( age < 18 ) { alert("Youre 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("Youre too young for a loan."); } else if ( score < 680 ) { alert("Your credit score is too low for a loan."); } else { alert("Youre approved for your loan."); }Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 122
  121. 121. 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; }Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 123
  122. 122. 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"; }Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 124
  123. 123. 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; }Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 125
  124. 124. 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; }Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 126
  125. 125. 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 }Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 127
  126. 126. 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 }Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 128
  127. 127. Agenda• How to code conditional expressions• How to code selection structures• How to code iteration structures
  128. 128. 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") ); }Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 130
  129. 129. 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 didnt enter any numbers."); } else { alert("The average is: " + average); }Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 131
  130. 130. 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 functionMurach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 132
  131. 131. 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);Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 133
  132. 132. 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 );Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 134
  133. 133. 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 functionMurach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 135
  134. 134. 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."); }Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 136
  135. 135. 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++; }Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 137
  136. 136. 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 ); } }Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 138
  137. 137. 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."); }Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 139
  138. 138. 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; } }Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 140
  139. 139. 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 10Murach’s JavaScript, C8 © 2009, Mike Murach & Associates, Inc. Slide 141
  140. 140. Exercise #6
  141. 141. js/invoice_total.js ;//determine and return discount percentswitch ( 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;}03/10/12 11:18 AM Slide 1

×