page 1 of 26 javascript/jscript ch 7,8,9,10 vadim parizher computer science department california...
TRANSCRIPT
Page 1 of 26
Javascript/JscriptCh 7,8,9,10
Vadim Parizher
Computer Science DepartmentCalifornia State University, Northridge
Spring 2003
Slides from text Book by Deitel, Deitel & Nieto
These slides are only for use in connection with the CPMP 496ECT course
Copying other than for private study strictly prohibitted
© Same as the book
Page 2 of 26
JavaScript scripting language Originally created by Netscape. Jscript is Microsoft’s version of JavaScript
Generates Dynamic HTML content by running “scripts” Object-Oriented Concepts are Fundamental
Document, Window, Math, Form
Writing to the document object using html syntax renders dynamic text on browser
Get input from the window object or Form Object Do math functions using math object
Introduction
Page 3 of 26
Basics
Syntax for invoking methods in the object object.method( “string”, “[additional arguments]” );
document.writeln( “<H1>argument</H1>” ); C like syntax Uses the writeln method in the browser’s document object
<SCRIPT>…</SCRIPT> tag: Encloses entire script Attribute LANGUAGE = “JavaScript”
Page 4 of 26
Document Object
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2 <HTML>
3 <!-- Fig. 13.2: welcome.html -->
4
5 <HEAD>
6 <TITLE>Printing a Line with Multiple Statements</TITLE>
7
8 <SCRIPT LANGUAGE = "JavaScript">
9 document.write( "<FONT COLOR='magenta'><H1>Welcome to " );
10 document.writeln( "JavaScript Programming!</H1></FONT>" );
11 </SCRIPT>
12
13 </HEAD><BODY></BODY>
14 </HTML>
Page 5 of 26
Window Object1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2 <HTML>
3 <!-- Fig. 13.4: welcome.html -->
4 <!-- Printing multiple lines in a dialog box -->
5
6 <HEAD>
7
8 <SCRIPT LANGUAGE = "JavaScript">
9 window.alert( "Welcome to\nJavaScript\nProgramming!" );
10 </SCRIPT>
11
12 </HEAD>
13
14 <BODY>
15 <P>Click Refresh (or Reload) to run this script again.</P>
16 </BODY>
17 </HTML>
Page 6 of 26
Windows, Documents and String handling1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">2 <HTML>3 <!-- Fig. 13.14: comparison.html -->4 <!-- Using if statements, relational operators, --> 5 <!-- and equality operators -->67 <HEAD>8 <TITLE>Performing Comparisons</TITLE>910 <SCRIPT LANGUAGE = "JavaScript">11 var first, // first string entered by user12 second; // second string entered by user1314 // read first number from user as a string15 first = window.prompt( "Enter first integer:", "0" );1617 // read second number from user as a string18 second = window.prompt( "Enter second integer:", "0" );1920 document.writeln( "<H1>Comparison Results</H1>" );21 document.writeln( "<TABLE BORDER = '1' WIDTH = '100%'>" );2223 if ( first == second )24 document.writeln( "<TR><TD>" + first + " == " + second + 25 "</TD></TR>" );2627 if ( first != second )28 document.writeln( "<TR><TD>" + first + " != " + second +29 "</TD></TR>" );3031 if ( first < second )32 document.writeln( "<TR><TD>" + first + " < " + second +
Page 7 of 26
Windows, Documents and String handling
33 "</TD></TR>" );
34
35 if ( first > second )
36 document.writeln( "<TR><TD>" + first + " > " + second +
37 "</TD></TR>" );
38
39 if ( first <= second )
40 document.writeln( "<TR><TD>" + first + " <= " + second +
41 "</TD></TR>" );
42
43 if ( first >= second )
44 document.writeln( "<TR><TD>" + first + " >= " + second +
45 "</TD></TR>" );
46
47 // Display results
48 document.writeln( "</TABLE>" );
49 </SCRIPT>
50
51 </HEAD>
52 <BODY>
53 <P>Click Refresh (or Reload) to run the script again</P>
54 </BODY>
55 </HTML>
Page 8 of 26
Output
If: First Integer = 123
Second Integer = 123
If: First Integer = 100
Second Integer = 200
If: First Integer = 200
Second Integer = 100
Page 9 of 26
JavaScript is Loosely Typed
JavaScript - loosely typed language Does not require variable to have type before use in program (unlike other
languages) Variable can contain a value of any data type JavaScript often converts between values of different types automatically
When declaring variables If not given value, variable has undefined value To indicate variable has no value, assign it null
Page 10 of 26
Math Object Compound Interest
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2 <HTML>
3 <!-- Fig. 15.6: interest.html -->
4
5 <HEAD>
6 <TITLE>Calculating Compound Interest</TITLE>
7
8 <SCRIPT LANGUAGE = "JavaScript">
9 var amount, principal = 1000.0, rate = .05;
10
11 document.writeln( "<TABLE BORDER = '1' WIDTH = '100%'>" );
12 document.writeln( "<TR><TD WIDTH = '100'><B>Year</B></TD>" );
13 document.writeln(
14 "<TD><B>Amount on deposit</B></TD></TR>" );
15
16 for ( var year = 1; year <= 10; ++year ) {
17 amount = principal * Math.pow( 1.0 + rate, year );
18 document.writeln( "<TR><TD>" + year + "</TD><TD>" +
19 Math.round( amount * 100 ) / 100 + "</TD></TR>" );
20 }
21
22 document.writeln( "</TABLE>" );
23 </SCRIPT>
24
25 </HEAD><BODY></BODY>
26 </HTML>
Page 12 of 26
Switch Statement1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">2 <HTML>3 <!-- Fig. 15.7: SwitchTest.html -->45 <HEAD>6 <TITLE>Switching between HTML List Formats</TITLE>78 <SCRIPT LANGUAGE = "JavaScript">9 var choice, // user’s choice10 startTag, // starting list item tag11 endTag, // ending list item tag12 validInput = true, // indicates if input is valid13 listType; // list type as a string1415 choice = window.prompt( "Select a list style:\n" + 16 "1 (bullet), 2 (numbered), 3 (lettered)", "1" );17 18 switch ( choice ) {19 case "1": 20 startTag = "<UL>";21 endTag = "</UL>";22 listType = "<H1>Bullet List</H1>"23 break;24 case "2":25 startTag = "<OL>";26 endTag = "</OL>";27 listType = "<H1>Ordered List: Numbered</H1>"28 break;29 case "3":30 startTag = "<OL TYPE = 'A'>";31 endTag = "</OL>";32 listType = "<H1>Ordered List: Lettered</H1>"
Page 13 of 26
Switch Statement
33 break;34 default:35 validInput = false; 36 }37 38 if ( validInput == true ) { 39 document.writeln( listType + startTag );40 41 for ( var i = 1; i <= 3; ++i )42 document.writeln( "<LI>List item " + i + "</LI>" );43 44 document.writeln( endTag );45 }46 else47 document.writeln( "Invalid choice: " + choice ); 48 </SCRIPT>4950 </HEAD>51 <BODY>52 <P>Click Refresh (or Reload) to run the script again</P>53 </BODY>54 </HTML>
Page 15 of 26
A Game of Chance - “CRAPS”
Rules of “craps” Player rolls 2 dice (6 faces/die, range: 1-6) Sum of spots on two upward faces calculate
If sum equals 7 or 11 – player wins If sum equals 2, 3 or 12 on first throw (called “craps”) – player loses If sum equals 4, 5, 6, 8, 9 or 10 on first throw – sum is players “point”
If game not over after first roll, player continues rolling If rolls sum equal to his “point” – player wins if rolls 7 before matching his “point” – player loses
Player continues rolling until game is over
Page 16 of 26
Input from Forms
Program can receive input from user through forms GUI Form Setup using Form:
GUI is enclosed inside an HTML Form<FORM NAME=“formName”>…<FORM> tags
Every GUI output is defined with the INPUT element<INPUT NAME = “inputName” TYPE = “text”>
Enter as many <INPUT> tags as needed
83<FORM NAME = "craps">84 <TABLE BORDER = "1">85 <TR><TD>Die 1</TD>86 <TD><INPUT NAME = "firstDie" TYPE = "text"></TD></TR>87 <TR><TD>Die 2</TD>88 <TD><INPUT NAME = "secondDie" TYPE = "text"></TD></TR>89 <TR><TD>Sum</TD>90 <TD><INPUT NAME = "sum" TYPE = "text"></TD></TR>91 <TR><TD>Point</TD>92 <TD><INPUT NAME = "point" TYPE = "text"></TD></TR>93 <TR><TD><INPUT TYPE = "button" VALUE = "Roll Dice" 94 ONCLICK = "play()"></TD></TR>95 </TABLE>96</FORM>
Page 17 of 26
83<FORM NAME = "craps">84 <TABLE BORDER = "1">85 <TR><TD>Die 1</TD>86 <TD><INPUT NAME = "firstDie" TYPE = "text"></TD></TR>87 <TR><TD>Die 2</TD>88 <TD><INPUT NAME = "secondDie" TYPE = "text"></TD></TR>89 <TR><TD>Sum</TD>90 <TD><INPUT NAME = "sum" TYPE = "text"></TD></TR>91 <TR><TD>Point</TD>92 <TD><INPUT NAME = "point" TYPE = "text"></TD></TR>93 <TR><TD><INPUT TYPE = "button" VALUE = "Roll Dice" 94 ONCLICK = "play()"></TD></TR>95 </TABLE>96</FORM>
Form Event Handling
Clicking on GUI button element causes an action <INPUT TYPE = “button” VALUE = “buttonLabel” ONCLICK =
“javaScriptFunctionName”> Function indicated is executed when button clicked Any user interaction with a GUI is called an event Event handling – JavaScript execution in response to an event GUI’s are located in the BODY of the HTML document
Page 18 of 26
Form Data output
Program can output results to a form Within a function, write a statement in the following format:
formName.InputName.value = Value to be output;
Outputing results to the Browser Status Bar Print text by typing
window.status = “text to be printed”;
Page 19 of 26
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">2 <HTML>3 <!-- Fig. 16.6: Craps.html -->45 <HEAD>6 <TITLE>Program that Simulates the Game of Craps</TITLE>78 <SCRIPT LANGUAGE = "JavaScript">9 // variables used to test the state of the game 10 var WON = 0, LOST = 1, CONTINUE_ROLLING = 2; 1112 // other variables used in program13 var firstRoll = true, // true if first roll14 sumOfDice = 0, // sum of the dice15 myPoint = 0, // point if no win/loss on first roll16 gameStatus = CONTINUE_ROLLING; // game not over yet1718 // process one roll of the dice19 function play()20 {21 if ( firstRoll ) { // first roll of the dice22 sumOfDice = rollDice(); 23 24 switch ( sumOfDice ) {25 case 7: case 11: // win on first roll26 gameStatus = WON;27 craps.point.value = ""; // clear point field28 break;29 case 2: case 3: case 12: // lose on first roll30 gameStatus = LOST;31 craps.point.value = ""; // clear point field32 break;33 default: // remember point
Page 20 of 26
34 gameStatus = CONTINUE_ROLLING;35 myPoint = sumOfDice;36 craps.point.value = myPoint; 37 firstRoll = false;38 }39 }40 else {41 sumOfDice = rollDice();42 43 if ( sumOfDice == myPoint ) // win by making point44 gameStatus = WON;45 else46 if ( sumOfDice == 7 ) // lose by rolling 747 gameStatus = LOST;48 }4950 if ( gameStatus == CONTINUE_ROLLING )51 window.status = "Roll again";52 else {53 if ( gameStatus == WON )54 window.status = "Player wins. " +55 "Click Roll Dice to play again.";56 else 57 window.status = "Player loses. " + 58 "Click Roll Dice to play again.";59 60 firstRoll = true;61 }62 }63 64 // roll the dice65 function rollDice()66 {
Page 21 of 26
67 var die1, die2, workSum; 6869 die1 = Math.floor( 1 + Math.random() * 6 );70 die2 = Math.floor( 1 + Math.random() * 6 );71 workSum = die1 + die2;7273 craps.firstDie.value = die1;74 craps.secondDie.value = die2;75 craps.sum.value = workSum;7677 return workSum;78 }79</SCRIPT>8081</HEAD>82<BODY>83<FORM NAME = "craps">84 <TABLE BORDER = "1">85 <TR><TD>Die 1</TD>86 <TD><INPUT NAME = "firstDie" TYPE = "text"></TD></TR>87 <TR><TD>Die 2</TD>88 <TD><INPUT NAME = "secondDie" TYPE = "text"></TD></TR>89 <TR><TD>Sum</TD>90 <TD><INPUT NAME = "sum" TYPE = "text"></TD></TR>91 <TR><TD>Point</TD>92 <TD><INPUT NAME = "point" TYPE = "text"></TD></TR>93 <TR><TD><INPUT TYPE = "button" VALUE = "Roll Dice" 94 ONCLICK = "play()"></TD></TR>95 </TABLE>96</FORM>97</BODY>98</HTML>