Anda di halaman 1dari 46

CHAPTER 3

JavaScript

1Inc. 2003 Prentice Hall,


All rights reserved.

Topics
Introduction Simple Program: Printing a Line of Text in a Web Page Obtaining User Input with Prompt Dialogs Dynamic Welcome Page Adding Integers Memory Concepts Arithmetic Decision Making: Equality and Relational Operators

Learning Outcomes
At the end of this lesson, students should be able to:
Write simple JavaScript programs. Use input and output statements. Understand basic memory concepts. Use arithmetic operators. Understand the precedence of arithmetic operators. Write decision-making statements. Use relational and equality operators.

What is JavaScript?
JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language A scripting language is a lightweight programming language JavaScript is usually embedded directly into HTML pages

Are Java and JavaScript the same?


NO! Java and JavaScript are two completely different languages in both concept and design!

Some Browsers do Not Support JavaScript


To prevent them from doing this, and as a part of the JavaScript standard, the HTML comment tag should be used to "hide" the JavaScript. Just add an HTML comment tag

Introduction
JavaScript scripting language
Enhances functionality and appearance Client-side scripting
Makes pages more dynamic and interactive

Foundation for complex server-side scripting Program development Program control

Simple Program: Printing a Line of Text in a Web Page

Inline scripting
Written in the <body> of a document <script> tag
Indicate that the text is part of a script type attribute
Specifies the type of file and the scripting language use
write

method

Write a text in the document

Simple Program: Printing a Line of Text in a Web Page


Escape character ( \ )
Indicates special character is used in the string
alert

method

Dialog box

The comment tags are used for browser that does not support JavaScript. The codes will not be displayed.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 7.1: welcome.html -->

<!-- Displaying a line of text --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>A First Program in JavaScript</title> <script type = "text/javascript"> <!-document.writeln( "<h1>Welcome to JavaScript Programming!</h1>" ); // --> </script> </head><body></body>

20 </html>

10

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 7.2: welcome2.html -->

<!-- Printing a Line with Multiple Statements --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head>

<title>Printing a Line with Multiple Statements</title> <script type = "text/javascript"> <!--

welcome2.html (1 of 1)

document.write( "<h1 style = \"color: magenta\">" ); document.write( "Welcome to JavaScript " + "Programming!</h1>" ); // --> </script> </head><body></body>

21 </html>

11

Simple Program: Printing a Line of Text in a Web Page

Unlike writeln, write does not position the output cursor in the XHTML document at the beginning of the next line after writing its argument.

12

Simple Program: Printing a Line of Text in a Web Page


Display the numbers 1 to 4 on the same line, with each pair of adjacent numbers separated by one space.
Using document.write document.write("1 "); document.write("2 "); document.write("3 "); document.write("4 "); Using document.writeln document.writeln("1"); document.writeln("2"); document.writeln("3"); document.writeln("4");
13

Spaces are needed

Simple Program: Printing a Line of Text in a Web Page

Line 15-16- Represents one statement. Statements in Java are separated by semicolons(;).JavaScript allows large statements to be split over many lines by using + operator.

14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 7.3: welcome3.html <!-- Printing Multiple Lines --> -->

<html xmlns = "http://www.w3.org/1999/xhtml">

<head><title>Printing Multiple Lines</title> <script type = "text/javascript"> <!--

welcome3.html 1 of 1

document.writeln( "<h1>Welcome to<br />JavaScript" + "<br />Programming!</h1>" ); // --> </script> </head><body></body>

19 </html>

15

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 7.4: welcome4.html -->

<!-- Printing multiple lines in a dialog box --> <html xmlns = "http://www.w3.org/1999/xhtml">

<head><title>Printing Multiple Lines in a Dialog Box</title> <script type = "text/javascript"> <!--

welcome4.html 1 of 1

window.alert( "Welcome to\nJavaScript\nProgramming!" ); // --> </script> </head> <body> <p>Click Refresh (or Reload) to run this script again.</p> </body>

22 </html>

16

17

Simple Program: Printing a Line of Text in a Web Page

Escape sequence \n \t \r

Description Newline. Position the screen cursor at the beginning of the next line. Horizontal tab. Move the screen cursor to the next tab stop. Carriage return. Position the screen cursor to the beginning of the current line; do not advance to the next line. Any characters output after the carriage return overwrite the characters previously output on that line.

Backslash. Used to represent a backslash character in a string. Double quote. Used to represent a double quote character in a string contained in double quotes. For example, window.alert( "\"in quotes\"" ); displays "in quotes" in an alert dialog. \' Single quote. Used to represent a single quote character in a string. For example, window.alert( '\'in quotes\'' ); displays 'in quotes' in an alert dialog. Fig. 7.5 Some common escape sequences.

\\ \"

18

Dynamic Welcome Page


A script can adapt the content based on input from the user or other variables

19

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- Fig. 7.6: welcome5.html --> <!-- Using Prompt Boxes -->

<html xmlns = "http://www.w3.org/1999/xhtml"> <head>

<title>Using Prompt and Alert Boxes</title> <script type = "text/javascript"> <!-var name; // string entered by the user

welcome5.html (1 of 2)

// read the name from the prompt box as a string name = window.prompt( "Please enter your name", "GalAnt" ); document.writeln( "<h1>Hello, " + name + ", welcome to JavaScript programming!</h1>" ); // --> </script>

20

23 24 25 26 27 28 <body> <p>Click Refresh (or Reload) to run this script again.</p> </body> </head>

29 </html>

welcome5.html (2 of 2)

21

Dynamic Welcome Page


When the user clicks OK, the value typed by the user is returned to the program as a string. This is the prompt to the user.

This is the default value that appears when the dialog opens.

This is the text field in which the user types the value.

Fig. 7.7

Prompt dialog displayed by the window objects prompt method.

22

Adding Integers
Prompt user for two integers and calculate the sum (Fig. 7.8) NaN (not a number)
parseInt

Converts its string argument to an integer

23

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 7.8: Addition.html --> <!-- Addition Program -->

<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>An Addition Program</title> <script type = "text/javascript"> <!-var firstNumber, secondNumber, number1, number2, sum;

Addition.html (1 of 2)

// first string entered by user // second string entered by user // first number to add // second number to add // sum of number1 and number2

// read in first number from user as a string firstNumber = window.prompt( "Enter first integer", "0" );

24

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

// read in second number from user as a string secondNumber = window.prompt( "Enter second integer", "0" ); // convert numbers from strings to integers number1 = parseInt( firstNumber ); number2 = parseInt( secondNumber ); // add the numbers sum = number1 + number2; // display the results document.writeln( "<h1>The sum is " + sum + "</h1>" ); // --> </script> </head> <body> <p>Click Refresh (or Reload) to run the script again</p> </body>

Addition.html (2 of 2)

44 </html>

25

26

Memory Concepts
Variable names correspond to locations in the computers memory. Every variable has a name, a type, and a value. Read value from a memory location.

27

Memory Concepts

number1
Fig. 7.9

45

Memory location showing the name and value of variable number1.

28

Memory Concepts
number1 number2 45 72

Fig. 7.10 Memory locations after values for variables number1 and number2 have been input.

29

Memory Concepts
number1 45

number2
sum

72
117

Fig. 7.11 Memory locations after calculating the sum of number1 and number2.

30

Arithmetic
Many scripts perform arithmetic calculations
Expressions in JavaScript must be written in straight-line form

31

Arithmetic
JavaScript operation Addition Subtraction Multiplication Division Arithmetic operator
+ * /

Algebraic expression f+7 x pc bm x / y or r mod s


-y

JavaScript expression
f + 7 p - c b * m x / y r % s

or

xy

% Remainder Fig. 7.12 Arithmetic operators.

Operation(s) Order of evaluation (precedence) Multiplication Evaluated second. If there are several such Division operations, they are evaluated from left to right. Modulus + or Addition Evaluated last. If there are several such operations, Subtraction they are evaluated from left to right. Fig. 7.13 Precedence of arithmetic operators.

Operator(s) *, / or %

32

Arithmetic
Step 1. y = 2 * 5 * 5 + 3 * 5 + 7;

2 * 5 is 10

(Leftmost multiplication)

Step 2. y = 10 * 5 + 3 * 5 + 7; 10 * 5 is 50 (Leftmost multiplication)

Step 3. y = 50 + 3 * 5 + 7; 3 * 5 is 15 (Multiplication before addition)

Step 4. y = 50 + 15 + 7; 50 + 15 is 65 (Leftmost addition)

Step 5. y = 65 + 7; 65 + 7 is 72 (Last addition) (Last operationplace72 into y )

Step 6. y = 72;
Fig. 7.14

Order in which a second-degree polynomial is evaluated.

33

Decision Making: Equality and Relational Operators Decision based on the truth or falsity of a condition
Equality operators Relational operators

34

Decision Making: Equality and Relational Operators


Standard algebraic equality operator or relational operator Equality operators = Relational operators > < JavaScript equality Sample or relational JavaScript operator condition == != > < >= <= x == y x != y x > y x < y x >= y x <= y Meaning of JavaScript condition x is equal to y x is not equal to y x is greater than y x is less than y x is greater than or equal to y x is less than or equal to y

Fig. 7.15 Equality and relational operators.

35

Decision Making: Equality and Relational Operators


Operators Associativity Type * / % left to right multiplicative + left to right additive < <= > >= left to right relational == != left to right equality = right to left assignment Fig. 7.17 Precedence and associativity of the operators discussed so far.

36

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- Fig. 7.16: welcome6.html -->

<!-- Using Relational Operators -->

<html xmlns = "http://www.w3.org/1999/xhtml"> <head>

<title>Using Relational Operators</title> <script type = "text/javascript"> <!--

welcome6.html (1 of 3)
// current date and time

var name, // string entered by the user now = new Date(), hour = now.getHours(); // current hour (0-23) // read the name from the prompt box as a string name = window.prompt( "Please enter your name", "GalAnt" ); // determine whether it is morning if ( hour < 12 ) document.write( "<h1>Good Morning, " );

37

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

// determine whether the time is PM if ( hour >= 12 ) { // convert to a 12 hour clock hour = hour - 12; // determine whether it is before 6 PM if ( hour < 6 )

document.write( "<h1>Good Afternoon, " ); // determine whether it is after 6 PM if ( hour >= 6 ) document.write( "<h1>Good Evening, " ); } document.writeln( name +

welcome6.html (2 of 3)

", welcome to JavaScript programming!</h1>" ); // --> </script> </head>

38

47 48 49 50

<body> <p>Click Refresh (or Reload) to run this script again.</p> </body> </html>

welcome6.html (3 of 3)

39

Sample Program 1
Write a script that gets from the user the radius of a circle and outputs XHTML text that displays the circles diameter, circumference and area. Use the constant value 3.14159 for PI. [Note: You may also use the predefined constant Math.PI for the value of PI. This constant is more precise than the value 3.14159. The Math object is defined by Java-Script and provides many common mathematical capabilities.] Use the following formulas (r is the radius): diameter = 2r, circumference = 2PIr, area = PIr2. INPUT: radius of a circle OUTPUT: circles diameter, circumference and area RELEVANT FORMULA: PI= 3.14159 diameter = 2r, circumference = 2PIr, area = PIr2
40

Application of JavaScript
There are two parts of an HTML document; <head> and <body>. JavaScript scripts can appear in either part of a document, depending on their purpose. Scripts that produce content only when requested or that react to user interactions are placed in the head of the document.
41

Application of JavaScript
Example: function definitions and code associated with form elements, such as buttons. Scripts that are to be interpreted just once, when the interpreter finds them, are placed in the document body.

42

Application of JavaScript
Example: Simple Calculator
Source: http://dynamicdrive.com/dynamicindex11/cal.htm

43

Application of JavaScript
Example: Text Area Max Length Script
Source: http://www.dynamicdrive.com/dynamicindex16/maxlength.htm

44

Application of JavaScript
Example: Form validation
(Source: http://www.w3schools.com/jS/js_form_validation.asp)

JavaScript can be used to validate data in HTML forms before sending off the content to a server. Form data that typically are checked by a JavaScript could be:
has the user left required fields empty? has the user entered a valid e-mail address? has the user entered a valid date? has the user entered text in a numeric field?

45

Web Resources
http://www.w3schools.com/js/default.asp http://wp.netscape.com/eng/mozilla/3.0/handbook/java script/index.html http://webdeveloper.com/javascript/javascript_js_tutori al.html http://www.hotscripts.com

46

Anda mungkin juga menyukai