1 / 51

Javascript fundamentals (continue)

Javascript fundamentals (continue). Visual Web Developer 2005. http://msdn.microsoft.com/vstudio/express/vwd/download/ Acknowledgement: Thanks to Andrew J. Hayes for providing this link. Example. <script language=javascript> var name="William"; var hometown ="Chico";

Download Presentation

Javascript fundamentals (continue)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Javascript fundamentals (continue)

  2. Visual Web Developer 2005 • http://msdn.microsoft.com/vstudio/express/vwd/download/ • Acknowledgement: Thanks to Andrew J. Hayes for providing this link.

  3. Example <script language=javascript> var name="William"; var hometown ="Chico"; function greetme() { var name="Daniel"; document.bgColor="cyan"; document.write("<h2> In function, <em> name </em> is "+name); document.write(" and <em> hometown </em> is "+hometown); } greetme(); document.write("<h2> Out of the function, <em> name </em> is "+name); document.write(" and <em> hometown </em> is "+hometown); </script> Global variables Local variable

  4. Example

  5. Variable Scope • The “scope” of a variable refers to the context of it’s existence • Two scopes • Global: variable is created outside of a function • Local (private): variable is created inside a function and exists only within the function

  6. Declaring a Variable • Syntax: var <variable name> [= <value> ]; For example: var playerScore; var playerScore = 0;

  7. Naming a Variable • Variable Names (also referred to as Identifiers) must begin with a letter or an underscore and cannot be a reserved word. • Variables are case sensitive and may not contain a space. Example: part_no _part_no part.no +part_no Part_No %Part_No

  8. Declaring a Variable • Variables can be assigned literal data, operations on variables, and logical expressions • var myScore = 100; • var newScore = myScore + yourScore; • var highScore = (myScore > yourScore); • Declaring a variable without giving it a value will cause an “undefined” value to be assigned • var partNumber • partNumber would have a value of “undefined” • Variables cannot be named using reserved words

  9. Declaring a Variable <script language="javascript"> var temperatureYesterday = 100; var temperatureToday = temperatureYesterday; window.alert("Yesterday's Temperature = " + temperatureYesterday); window.alert("Today's Temperature = " + temperatureToday); </script>

  10. Result

  11. Initializing a Variable <script language="javascript"> var firstName; var familyName; var address1; var address2; var city; var state; var zip; var country; var ourCustomer;

  12. Initializing a Variable (continued) function dispVars(){ window.alert("firstName = " + firstName); window.alert("familyName = " + familyName); window.alert("address1 = " + address1); window.alert("address2 = " + address2); window.alert("city = " + city); window.alert("state = " + state); window.alert("zip = " + zip); window.alert("country = " + country); window.alert("ourCustomer = " + ourCustomer); } </script> <body> <input type="button" value="Display Variables" onClick="dispVars();"> </body>

  13. Initializing a Variable with Values <script language="javascript"> var firstName = ""; var familyName = null; var address1 = null; var address2 = null; var city = null; var state =''; var zip = 0; var country ="USA"; var ourCustomer = true;

  14. Changing the Value of a Variable function changeValues(){ firstName = "Elizabeth"; familyName = "Jones"; address1 = "Rose Cottage"; address2 = "25 City Road"; city = "Richmond"; state ='VA'; zip = 23227; country ="USA"; ourCustomer = false; }

  15. Changing the Value of a Variable(continued) <body> <input type="button" value="Display Variables" onClick="dispVars();"> <input type="button" value="Change Variable Values and Display" onClick="changeValues();dispVars()"> </body>

  16. Character Escaping • String Expressions can contain characters that have a special meaning to JavaScript • For example, when using the backslash character in a string it might be misinterpreted unless escaped • var myPath = “C:\MyDocuments\JavaScriptBook” • var myPath = “C:\\MyDocuments\\JavaScriptBook”

  17. Typeof Operator • Returns a string to identify the type of its operand. • Example: var a =1; document.write(“data type of a is “+ typeof(a));

  18. Displaying Variable Values <script type="text/javascript"> var headline1 = "Bank fees increase by 10 percent"; var headline2 = "Mortgage rates at 25 year lows"; var headline3 = "NASDAQ closes above 2000"; document.write("<h1>Breaking news: " + headline1 + "</h1>"); document.write("<h1>Yesterday's news: " + headline2 + "</h1>"); document.write("<h1>Last week's news: " + headline3 + "</h1>"); document.write("<p>News Stories</p>"); document.write("<br><a href=\"" + headline1 + ".html\">" + headline1 + "</a>"); document.write("<br><a href=\"" + headline2 + ".html\">" + headline2 + "</a>"); document.write("<br><a href=\"" + headline3 + ".html\">" + headline3 + "</a>"); </script>

  19. Using Mathematical Operators <script type="text/javascript"> var x = 10; var y = 5; document.write("<br>x + y = " + (x+y)); document.write("<br>x - y = " + (x-y)); document.write("<br>x * y = " + (x*y)); document.write("<br>x / y = " + (x/y)); document.write("<br>x % y = " + (x%y)); document.write("<br> -x = " + (-x)); document.write("<br>--x = " + (--x)); document.write("<br>++x = " + (++x)); </script>

  20. Summary • Variables can store information to be processed • Variable names should be descriptive of what they contain • Variables in JavaScript are not strictly typed • Operators can be used to manipulate the contents of variables • The scope of a variable can be global or private • The keyword var is used to create variables • Variables can be assigned literal data, operations on variables, and logical expressions

  21. Summary (continued) • Declaring a variable without giving it a value will cause an “undefined” value to be assigned • Variables cannot be named using reserved words • Character escaping can be used to include specific characters in text strings that would otherwise be misinterpreted

  22. Lab 2 Step 1:Type or copy & paste the following into your Textpad <html> <head> <title>Untitled Page</title> </head> <body> </body> </html>

  23. Lab 2 Step 2: Insert a script that contains four variables in the head of the document: - the first one contains your name - the second contains a value 0 - the third one is declared but has no value - the fourth one contains an empty string. Step 3: In the body of the document, write another script to display the type of each variable, as well as its value.

  24. Objectives • Use conditional statements, including if and if . . . else • Implement looping statements, including for, for . . . in, while,do . . . while, break, and continue • Know when to use label, switch, and withstatements

  25. If Syntax if(expression){ statement block } Example var numbOfItems = 0; if(numbOfItems > 3){ window.alert(“You have reached the limit.”); }

  26. If Else Syntax if(expression){ statement block } else{ else statement block } Example var numbOfItems = 0; if(numbOfItems > 3){ window.alert(“You have reached the limit.”); } else{ window.alert(“Please choose an Item.”); }

  27. Try / Catch / Finally try {    if(answer == 1){       throw "Error1“; }    else if(answer == 2){      throw "Error2“; } } catch(er) {   if(er == "Error1"){       window.alert(“Invalid Data Type"); }   if(er == "Error2"){       window.alert(“Unterminated String”); } } finally( window.alert(“Unknow Error”); }

  28. For Syntax for (starting value; expression; increment/decrement){ statement block } Example for (firstNum = 1; firstNum < 11; firstNum++){ window.alert(firstNum); }

  29. For In Syntax for(variable in array){ statement block } Example var controlStructures = new Array(“For”,”For In”,”While”,”Do While”); for(controlStruc in controlStructures){ document.write(controlStructures[controlStruc]); document.write(“<br>”); }

  30. While Syntax while(expression){ statement block } Example var counter = 1; while(counter <= 10){ document.write(counter); document.write(“<br>”); counter++; }

  31. Do While Syntax do{ statement block } while(expression is true) Example var counter = 1; do( window.alert(counter); counter++; } while(counter <= 10)

  32. Break Example var counter = 1; while(counter > 0){ document.write(counter); counter++; // if (counter == 5){ // break; } Syntax break;

  33. Continue Syntax continue; Example for(counter = 1; counter <=50; counter++){ if(counter % 2 == 0){ continue; } document.write(counter); document.write(“<br>”); }

  34. Switch Syntax switch(expression){case x:  statement block break;case y:  statement block break;default:  statement block; break;} Example switch(selection){case 2:  population = 2,688,418; break;case 5:  population = 1,711,263; break; }

  35. Using an If Else structure <script type="text/javascript"> function checkIfEligible() { if (document.homeLoanApplication.annualIncome.value<50000) { window.alert("You are not eligible to apply for a home loan."); } else { window.alert("You are eligible to apply for a home loan."); } } </script>

  36. Using an If Else structure <form name="homeLoanApplication"> Annual Income: $ <input type="Text" name="annualIncome"> <input type="submit" value="Check Eligibility" onClick="checkIfEligible();"> </form>

  37. Multiple If Conditions <script type="text/javascript"> function checkIfEligible() { if (document.homeLoanApplication.annualIncome.value<50000||document.homeLoanApplication.liabilities.value>100000) { window.alert("You are not eligible to apply for a home loan."); } else { window.alert("You are eligible to apply for a home loan."); } } </script>

  38. Multiple If Conditions (continued) <form name="homeLoanApplication"> Annual Income: $ <input type="Text" name="annualIncome"> Current Liabilities: $ <input type="Text" name="liabilities"> <input type="Submit" value="Submit" onClick="checkIfEligible()"> </form>

  39. Using a While Loop <script type=“text/javascript”> function printPayments() { var principal=document.homeLoanCalculator.principal.value; var years=document.homeLoanCalculator.years.value; var annualPayment=principal/years; var y=1; document.write("<table border=\"1\" width=\"100%\">"); document.write("<tr>"); document.write("<td>Year</td>"); document.write("<td>Value</td>"); document.write("</tr>");

  40. Using a While Loop (continued) while (years>0) { document.write("<tr>"); document.write("<td>"+y+"</td>"); document.write("<td>$"+principal+"</td>"); document.write("</tr>"); principal-=annualPayment; y++; years--; } document.write("</table>"); } </script>

  41. Using while loop <form name="homeLoanCalculator"> Outstanding Principal: $<input type="Text" name="principal"> Years to Pay: <input type="Text" name="years"> <input type="Submit" value="Submit" onClick="printPayments();">

  42. Using For <script type=“text/javascript”> function printPayments() { var principal=document.homeLoanCalculator.principal.value; var years=document.homeLoanCalculator.years.value; var annualPayment=principal/years; var y=1; document.write("<table border=\"1\" width=\"100%\">"); document.write("<tr>"); document.write("<td>Year</td>"); document.write("<td>Value</td>"); document.write("</tr>");

  43. Using For (continued) for (i=0; i<years; i++) { document.write("<tr>"); document.write("<td>"+y+"</td>"); document.write("<td>$"+principal+"</td>"); document.write("</tr>"); principal-=annualPayment; y++; } document.write("</table>"); } </script>

  44. Using For (continued) <form name="homeLoanCalculator"> Outstanding Principal: $<input type="Text" name="principal"> Years to Pay: <input type="Text" name="years"> <input type="Submit" value="Submit" onClick="printPayments();"> </form> </body> </html>

  45. Using a Switch Construct <HTML> <HTEAD> <SCRIPT language=javascript> var selobj = ""; function displaypopulation(selobj){ var population = 0; switch(selobj.selectedIndex){ case 0: population = "2,688,418"; break; case 1: population = "2,926,324"; break; case 2: population = "2,233,169"; break; case 3: population = "1,711,263"; break; } alert("Population of " + selobj.options[selobj.selectedIndex].value + " = " + population); } </SCRIPT>

  46. Using a Switch Construct (continued) </HEAD> <BODY onload=document.switchdoc.switchlist.focus();> <FORM name=switchdoc> <TABLE border=0> <TR> <TD vAlign=top>Display Population For: <SELECT onchange=“displaypopulation(this);” name=switchlist> <OPTION value=Kansas selected>Kansas <OPTION value=Iowa>Iowa <OPTION value=Utah>Utah <OPTION value=Nebraska>Nebraska </SELECT> <br><i>Census 2000</i> </TD> </TR> </TABLE> </FORM> </BO> </HTML>

  47. Summary • Using control structures allows your code to change the flow • Using this control brings more sophistication and power to your scripts • Using conditions and loops controls when certain blocks of code are executed • Loops can be predetermined or controlled by logic built into them • If Else control structures account for one of two possible choices

  48. Summary (continued) • Switch control structures allow for one of many possible code executions • Endless loops can be created by not incrementing or decrementing a counter variable or using a condition that never evaluates to false • While loops may not iterate at all – the expression is evaluated before the loop executes • Do While loops iterate at least once – the expression is not evaluated until the bottom of the structure

  49. Lab Step 1:Cut& paste this code <html > <head> <title>Untitled Page</title> <!– Insert your script here --> </head> <body> </body> </html>

  50. Lab Step 2: In the body of the HTML page, Create a HTML form that allows a user to enter the current points (integer), looks like the following:

More Related