Javascript fundamentals (continue). Visual Web Developer 2005 wd/download/.

51
Javascript fundamentals (continue)

Transcript of Javascript fundamentals (continue). Visual Web Developer 2005 wd/download/.

Page 1: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

Javascript fundamentals (continue)

Page 2: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

Visual Web Developer 2005

• http://msdn.microsoft.com/vstudio/express/vwd/download/

• Acknowledgement:Thanks to Andrew J. Hayes for providing this link.

Page 3: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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

Page 4: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

Example

Page 5: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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

Page 6: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

Declaring a Variable

• Syntax:var <variable name> [= <value> ];

For example:var playerScore;

var playerScore = 0;

Page 7: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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_nopart.no +part_noPart_No %Part_No

Page 8: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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

Page 9: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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>

Page 10: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

Result

Page 11: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

Initializing a Variable

<script language="javascript">var firstName;var familyName;var address1;var address2;var city;var state;var zip;var country;var ourCustomer;

Page 12: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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>

Page 13: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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;

Page 14: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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;

}

Page 15: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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>

Page 16: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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”

Page 17: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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));

Page 18: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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>

Page 19: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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>

Page 20: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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

Page 21: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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

Page 22: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

Lab 2

Step 1: Type or copy & paste the following into your Textpad

<html><head> <title>Untitled Page</title></head><body>

</body></html>

Page 23: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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.

Page 24: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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 with statements

Page 25: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

If

Syntaxif(expression){

statement block}

Examplevar numbOfItems = 0;if(numbOfItems > 3){

window.alert(“You have reached the limit.”);}

Page 26: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

If ElseSyntaxif(expression){

statement block}else{

else statement block}

Examplevar numbOfItems = 0;if(numbOfItems > 3){

window.alert(“You have reached the limit.”);}else{

window.alert(“Please choose an Item.”);}

Page 27: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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”);}

Page 28: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

For

Syntaxfor (starting value; expression; increment/decrement)

{statement block

}

Examplefor (firstNum = 1; firstNum < 11; firstNum++){

window.alert(firstNum);}

Page 29: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

For InSyntaxfor(variable in array){

statement block

}

Examplevar controlStructures = new Array(“For”,”For In”,”While”,”Do

While”);

for(controlStruc in controlStructures){document.write(controlStructures[controlStruc]);document.write(“<br>”);

}

Page 30: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

WhileSyntaxwhile(expression){

statement block}

Examplevar counter = 1;while(counter <= 10){

document.write(counter);document.write(“<br>”);counter++;

}

Page 31: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

Do WhileSyntaxdo{

statement block}while(expression is true)

Examplevar counter = 1;do(

window.alert(counter);counter++;

}while(counter <= 10)

Page 32: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

Break

Example var counter = 1;while(counter > 0){

document.write(counter);counter++;// if (counter == 5){// break;

}

Syntax break;

Page 33: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

Continue

Syntaxcontinue;

Examplefor(counter = 1; counter <=50; counter++){

if(counter % 2 == 0){continue;

}document.write(counter);document.write(“<br>”);

}

Page 34: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

Switch

Syntaxswitch(expression){

case x:  statement block break;

case y:  statement block break;

default:  statement block; break;}

Exampleswitch(selection){case 2:  population = 2,688,418; break;

case 5:  population = 1,711,263; break;

}

Page 35: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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>

Page 36: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

Using an If Else structure

<form name="homeLoanApplication"> Annual Income: $ <input type="Text"

name="annualIncome"> <input type="submit" value="Check Eligibility"

onClick="checkIfEligible();"> </form>

Page 37: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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>

Page 38: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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>

Page 39: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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>");

Page 40: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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>

Page 41: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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();">

Page 42: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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>");

Page 43: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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>

Page 44: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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>

Page 45: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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>

Page 46: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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>

Page 47: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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

Page 48: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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

Page 49: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

Lab

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

</body></html>

Page 50: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

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:

Page 51: Javascript fundamentals (continue). Visual Web Developer 2005  wd/download/.

Lab

Step 3: Create a script that does the following:

- If the current point is greater than 90, prompt “ You earn an A”

- If the current point is less than 90 but greater than 80, prompt “ You earn a B”

- Otherwise, prompt “You need to work harder”