+ All Categories
Home > Documents > JavaScript. 2 References Chapter 13, JavaScript/JScript: Introduction to Scripting from e-Business &...

JavaScript. 2 References Chapter 13, JavaScript/JScript: Introduction to Scripting from e-Business &...

Date post: 18-Jan-2016
Category:
Upload: roderick-kelley
View: 245 times
Download: 0 times
Share this document with a friend
57
JavaScript
Transcript

JavaScript

2

References• Chapter 13, JavaScript/JScript: Introduction to

Scripting from e-Business & e-Commerce: How to Program by Dietel, Dietel and Nieto.

• Chapter 14, JavaScript/JScript: Control Structures I from e-Business & e-Commerce: How to Program by Dietel, Dietel and Nieto.

• Chapter 15, JavaScript/JScript: Control Structures II from e-Business & e-Commerce: How to Program by Dietel, Dietel and Nieto.

3

Introduction• Originally developed by Netscape.

– Script language for programs that are embedded in webpages and executed on the clients upon download.

– Internet browsers have JavaScript interpreter which processes the commands in a script written in JavaScript.

• Microsoft’s version of JavaScript is called JScript.

• JavaScript/JScript standardised by ECMA (European Computer Manufacturer’s Association) as ECMAScript.

4

Embedding Script in HTML Pages• Script embedded in between the <HEAD> and

</HEAD> tags of an HTML page are executed before the body of the HTML page is displayed.

• Inline scripting allows JavaScript code to be written in the BODY section of an HTML page.

• Script is contained within <SCRIPT> and </SCRIPT> tags.

• The LANGUAGE attribute of the <SCRIPT> tag specifies the scripting language in which the script is authored.– Value of LANGUAGE attribute for JavaScript is

“JavaScript”.

5

HelloWorld in JavaScript

<HTML>

<!-- A Simple JavaScript program -->

<HEAD>

<TITLE>

JavaScript HelloWorld.

</TITLE>

<SCRIPT LANGUAGE="JavaScript">

document.write("<H1 ALIGN='center'><U>Hello World</U></H1><BR>");

document.write("<P ALIGN='center'> This world's simplest");

document.writeln(" JavaScript program</P>");

</SCRIPT>

</HEAD>

<BODY>

<P>Authored by Omar Bashir</P>

</BODY>

</HTML>

6

HelloWorld in JavaScript (Contd.)

• JavaScript is case sensitive.

• Current HTML page is represented by the object document.

• write method of the document object instructs the browser to display the argument string.

• If the argument string contains HTML elements, these are processed by the browser.

• writeln functions similar to write except that it positions the text cursor to the beginning of the next line.

7

HelloWorld in a Pop-up

<HTML>

<!-- A JavaScript program for a Popup-->

<HEAD>

<TITLE>

JavaScript HelloWorld in a Popup.

</TITLE>

<SCRIPT LANGUAGE="JavaScript">

window.alert("Hello World\nfrom\nJavaScript");

document.write("<P ALIGN='center'> This world's simplest");

document.writeln(" JavaScript program</P>");

</SCRIPT>

</HEAD>

<BODY>

<P>Authored by Omar Bashir</P>

</BODY>

</HTML>

8

HelloWorld in a Pop-up (Contd.)

• Browser is represented as the window object.

• alert method of the window object pops up a dialog box showing the contents of the argument to the alert method.

• The dialog box contains an OK button that allows the users to dismiss (hide) the dialog box by clicking on it.

• Dialog boxes only display text and they do not render HTML.– Specifying HTML elements to the alert method

causes the tags to be displayed.

9

Entering Data using JavaScript

• Variables need to be declared using the var keyword.

• prompt method of the window object is used to enter data.

• Arguments to the prompt method– First argument specifies the prompt to be displayed

in the dialog box.– Second argument is optional and specifies the

default text in the text box of the dialog box.

10

Entering Data using JavaScript (Contd.)

• All data is entered as text.– To convert text data into integers, it is passed to

parseInt function, which returns an integer represented by the text argument.

– To convert text data into real numbers, it is passed to parseFloat function, which returns a real number represented by the text argument.

• The dialog box has two buttons.– Clicking on OK returns to the script the data entered

in the textbox.– Clicking on Cancel returns null

11

Data Types in JavaScript• JavaScript is a loosely typed language.• JavaScript does not require variables to have a

type before they are used in a program.• A variable in JavaScript can contain value of

any data type. • In many situations JavaScript automatically

converts between values of different types.• A variable when declared but not assigned a

value has an undefined value and cannot be used.

• A variable can be assigned null to indicate that it does not contain a value.

12

Simple Text Input<HTML>

<HEAD>

<TITLE>

JavaScript Data Entry Example.

</TITLE>

<SCRIPT LANGUAGE="JavaScript">

var YourName;

YourName = window.prompt("What is your name","Enter your name here");

document.write("<H1 ALIGN='center'> Hello " + YourName);

document.writeln(", how do you do</H1>");

</SCRIPT>

</HEAD>

<BODY>

<P>Authored by Omar Bashir</P>

</BODY>

</HTML>

13

Multiple Inputs

<HTML>

<HEAD>

<TITLE>

JavaScript Data Entry Example.

</TITLE>

<SCRIPT LANGUAGE="JavaScript">

var YourName, YourAgeStr,YourAgeInt;

var YourAgeAfter10Years;

YourName = window.prompt("What is your name","Enter your name here");

YourAgeStr = window.prompt("What is your age");

YourAgeInt = parseInt(YourAgeStr);

14

Multiple Inputs (Contd.)

YourAgeAfter10Years = YourAgeInt + 10;

document.write("<H1 ALIGN='center'> Hello " + YourName);

document.writeln(", how do you do</H1>");

document.writeln("Today you are " + YourAgeInt + " years old.");

document.write("After 10 years you will be ");

document.writeln(YourAgeAfter10Years + " years old");

</SCRIPT>

</HEAD>

<BODY>

<P>Authored by Omar Bashir</P>

</BODY>

</HTML>

15

Arithmetic Operations

Operation SymbolArithmetic Expression

JavaScript Representation

Addition + a+b a+b

Subtraction - c-d c-d

Multiplication * bm b*m

Division / xy x/y

Modulus % r mod s r%s

16

Arithmetic Exercise<HTML>

<HEAD>

<TITLE>

JavaScript Arithmetic Operations Example.

</TITLE>

<SCRIPT LANGUAGE="JavaScript">

var FirstNumberStr, FirstNumber;

var SecondNumberStr, SecondNumber;

var Sum, Difference, Product, Division, Mod;

FirstNumberStr = window.prompt("Enter the first number","0");

SecondNumberStr = window.prompt("Enter the second number","0");

FirstNumber = parseFloat(FirstNumberStr);

SecondNumber = parseFloat(SecondNumberStr);

Sum = FirstNumber + SecondNumber;

Difference = FirstNumber - SecondNumber;

Product = FirstNumber * SecondNumber;

Division = FirstNumber/SecondNumber;

Mod = FirstNumber % SecondNumber;

17

Arithmetic Exercise (Contd.)

document.write("FirstNumber = " + FirstNumber);

document.write("<BR>SecondNumber = " + SecondNumber);

document.write("<BR>Sum = " + Sum);

document.write("<BR>Difference = " + Difference);

document.write("<BR>Product = " + Product);

document.write("<BR>Division = " + Division);

document.write("<BR>Modulus = " + Mod);

</SCRIPT>

</HEAD>

<BODY>

<P>Authored by Omar Bashir</P>

</BODY>

</HTML>

18

Rules of Operator Precedence• Parenthesis

– Operators in expressions contained between a left parenthesis and its corresponding right parenthesis are evaluated first.

– Innermost pair of parenthesis is evaluated first.

• Multiplication, division and modulus– Precedence lower than expressions contained in

parenthesis.– Applied left to right.

• Addition and subtraction– Lowest precedence– Applied left to right.

19

Assignment Operators

• = Simple assignment operator– Assigns the value of the expression on the right to

the variable on the left.

• += Addition assignment operator– Adds the value of the expression on the right to the

value of the variable on the left and assigns the result to the variable on the left.

• -= Subtraction assignment operator– Subtracts the value of the expression on the right to

the value of the variable on the left and assigns the result to the variable on the left.

20

Assignment Operators (Contd.)

• *= Multiplication assignment operator– Multiplies the value of the expression on the right to

the value of the variable on the left and assigns the result to the variable on the left.

• /= Division assignment operator– Divides the value of the expression on the right to

the value of the variable on the left and assigns the result to the variable on the left.

• %= Modulus assignment operator– Evaluates the modulus of the value of the

expression on the right with the value of the variable on the left and assigns the result to the variable on the left.

21

Increment and Decrement Operators

• Pre-increment– ++a– Increments the value of the variable by 1 and then

returns the incremented value to the expression.

• Post-increment– a++– Returns the value of the variable to the expression

and then increments the value of the variable by 1.

22

Increment and Decrement Operators

• Pre-decrement– --a– Decrements the value of the variable by 1 and then

returns the decremented value to the expression.

• Post-decrement– a--– Returns the value of the variable to the expression

and then decrements the value of the variable by 1.

23

Control Structures• Sequence structure

– Unless directed, statements in a JavaScript program are executed in the sequence in which they occur.

• Selection structure– Single selection structure

• If the condition is true, a statement is executed, otherwise it is not executed.

– Double selection structure• If the condition is true a statement is executed, otherwise

a different statement is executed.

– Multiple selection structure• Selection is made from a number of different alternatives

based on the value of the control variable.

24

Control Structures (Contd.)

• Repetitive structure– A sequence of instructions is repeated for as long

as a specific condition is true.

• Programs are created by connecting control structures.

• Types of control structure connections– Control structure stacking

• Control structures attached to one another by connecting the exit point of one to the entry point of the other.

– Control structure nesting• One control structure existing within another control

structure.

25

Decision Making using if Statement

• Single selection structure.

• if structure allows a programs to make decisions based on truth or falsity of a condition.– If the condition is true, the statement in the if block

is executed.

• Conditions in the if statements are formed using the equality and relational operators.

• General syntax– if (condition)

statement;

26

Equality, Inequality and Relational Operators

Type Symbol Example Description

Equality

Is equal to

== x == y x is equal to y.

Equality

Is not equal to

!= x != y x is not equal to y.

Relational

Greater than

> x > y x is greater than y.

Relational

Less then

< x < y x is less than y.

Relational

Greater than or equal to

>= x >= y x is greater than or equal to y.

Relational

Less than or equal to

<= x <= y x is less than or equal to y.

27

Example: if Structure

<HTML>

<HEAD>

<TITLE>

JavaScript if Example.

</TITLE>

<SCRIPT LANGUAGE="JavaScript">

var FirstStr;

var SecondStr;

FirstStr = window.prompt("Enter the first value","Enter here");

SecondStr = window.prompt("Enter the second number","Enter here");

if (FirstStr == SecondStr)

document.write(FirstStr + " == " + SecondStr + "</BR>");

if (FirstStr != SecondStr)

document.write(FirstStr + " != " + SecondStr + "</BR>");

28

Example: if Structure (Contd.)

if (FirstStr > SecondStr)

document.write(FirstStr + " > " + SecondStr + "</BR>");

if (FirstStr < SecondStr)

document.write(FirstStr + " < " + SecondStr + "</BR>");

if (FirstStr >= SecondStr)

document.write(FirstStr + " >= " + SecondStr + "</BR>");

if (FirstStr <= SecondStr)

document.write(FirstStr + " <= " + SecondStr + "</BR>");

</SCRIPT>

</HEAD>

<BODY>

<P>Authored by Omar Bashir</P>

</BODY>

</HTML>

29

if-else Structure

• Double selection structure.

• General syntax– if condition

statement1;else

statement2;– If the condition following the if keyword is true,

statement1 is executed, otherwise statement2 is executed.

• Statements following if and else clauses can be compound statements enclosed within braces.

30

Example: if-else Structure

<HTML>

<HEAD>

<TITLE>

JavaScript if-else Example.

</TITLE>

<SCRIPT LANGUAGE="JavaScript">

var MarksStr;

var Marks;

MarksStr = window.prompt("Enter marks obtained in exam","0");

Marks = parseInt(MarksStr);

if (Marks >= 50)

{

document.write("<H1> <FONT COLOR='green'>");

document.write("Congratulations, you have passed.");

document.write("</FONT> </H1>");

}

31

Example: if-else Structure (Contd.)

else

{

document.write("<H1> <FONT COLOR='red'>");

document.write("Sorry, you have failed, better luck next time.");

document.write("</FONT> </H1>");

}

</SCRIPT>

</HEAD>

<BODY>

<P>Authored by Omar Bashir</P>

</BODY>

</HTML>

32

Example: Nested if-else<HTML>

<HEAD>

<TITLE>

JavaScript if-else Example.

</TITLE>

<SCRIPT LANGUAGE="JavaScript">

var Offense;

var SpeedStr,Speed;

var Fine;

Offense = window.prompt("Enter Offence Committed","");

if (Offense == "parking")

Fine = 25;

else

if (Offense == "overspeeding")

{

SpeedStr = window.prompt("Enter Speed","0");

Speed = parseInt(SpeedStr);

33

Example: Nested if-else (Contd.)

if (Speed > 180)

Fine = 250;

else

if (Speed > 150)

Fine = 220;

else

if (Speed > 100)

Fine = 150;

}

else

Fine = -1;

if (Fine != -1)

document.write("You are fined " + Fine + " AED");

else

document.write("Could not ascertain your offense");

</SCRIPT>

34

Example: Nested if-else (Contd.)

</HEAD>

<BODY>

<P>Authored by Omar Bashir</P>

</BODY>

</HTML>

35

The while Repetition Structure

• Allows repetition of a statement (or a group of statements) while a condition remains true.

• General syntax– while (condition)

statement;– statement can be simple or compound.– statement is repeated while condition remains true.

36

Types of Repetitions• Counter Controlled Repetitions

– A variable is used as a counter to control the number of times the body of the loop (i.e., statement) is executed.

– Also referred to as the definite repetition.

• Sentinel Controlled Repetitions– A sentinel value (also known as the flag value or

signal value) is used to indicate the end of repetition.

– As the number of repetitions is not known before the initiation of the loop, it is also referred to as the indefinite repetition.

37

Counter Controlled Repetition

• Counter controlled repetitions are controlled by a counter variable.– The initial value for the counter is specified.– The expression that updates the value of the

counter variable has to be specified.– The condition that tests for the final value of the

control variable to determine whether looping should continue has to be defined.

38

Example: Definite Repetition

<HTML>

<HEAD>

<TITLE>

JavaScript Counter Controlled Repetition Example.

</TITLE>

<SCRIPT LANGUAGE="JavaScript">

var NumberStr;

var Number;

var Counter;

var Factorial;

NumberStr = window.prompt("Enter the number to find a factorial","0");

Number = parseInt(NumberStr);

39

Example: Definite Repetition(Contd.)

Factorial = 1;

Counter = Number;

while (Counter > 1)

{

Factorial = Counter * Factorial;

Counter--;

}

document.write("<EM>Factorial of " + Number + " is " + Factorial);

document.write("</EM><BR>");

</SCRIPT>

</HEAD>

<BODY>

<P>Authored by Omar Bashir</P>

</BODY>

</HTML>

40

Example: Indefinite Repetition<HTML>

<HEAD>

<TITLE>

JavaScript Sentinel Controlled Repetition Example.

</TITLE>

<SCRIPT LANGUAGE="JavaScript">

var NumberStr;

var Number;

var Min, Max, Average, Sum, Count;

Number = 0;

Sum = 0.0;

Count = 0;

Min = 0;

Max = 0;

41

Example: Indefinite Repetition(Contd.)

while (Number >= 0)

{

NumberStr = window.prompt("Enter marks, -1 to abort","0");

Number = parseInt(NumberStr);

if (Number >= 0)

{

Sum += Number;

Count++;

if (Number > Max)

Max = Number;

else if (Number < Max)

Min = Number

}

}

42

Example: Indefinite Repetition(Contd.)

Average = Sum/Count;

document.write("<EM>Average of " + Count + " students is ");

document.write(Average + "<BR>");

document.write("Min is " + Min + "<BR>");

document.write("Max is " + Max + "<BR>");

</SCRIPT>

</HEAD>

<BODY>

<P>Authored by Omar Bashir</P>

</BODY>

</HTML>

43

for Repetition Structure

• for repetition structure allows handling of all counter controlled operations in a single statement.

• Syntax– for(initialisation;condition;update)

statement;• The counter variable is initialised in the initialisation

expression.• The counter variable is tested in condition expression. If

true, the statement is executed.• After the statement has been executed, the update

expression updates the counter variable.

44

Example: for Loop<HTML>

<HEAD>

<TITLE>for in JavaScript </TITLE>

<SCRIPT>

var InitialSalaryStr;

var InitialSalary;

var Increment = 0.1;

var Year;

var CurrentYear;

InitialSalaryStr = window.prompt("Enter Initial Salary","");

if (InitialSalaryStr == null)

{

document.write("<EM>Invalid value</EM><BR>");

}

else

45

Example: for Loop (Contd.)

{

InitialSalary = parseInt(InitialSalaryStr);

document.write("<U><H4>Initial Salary:"+InitialSalary+ "| Increment:"+ Increment +"</U></H4><BR>");

for (Year=1;Year<6;++Year)

{

InitialSalary = (1 + Increment) * InitialSalary;

document.write(Year+"|"+InitialSalary+"<BR>");

}

}

</SCRIPT>

</HEAD>

<BODY>

<P>Prepared by Omar Bashir</P>

</BODY>

</HTML>

46

Multiple Choices with switch• if is a single selection structure.

• if else is a double selection structure.

• switch provides a multiple selection structure.– The algorithm contains a series of decisions in

which a variable or expression is tested separately for each of the values.

– Different actions are specified for each of the values the control variable or expression can assume.

47

Multiple Choices with switch(Contd.)

• Syntax– switch (controlling_expression)

{case value1:

statement1;break;case value2;

statement2;break;default;

default_statement;}

48

Multiple Choices with switch(Contd.)

• Processing– When the flow of control reaches the switch statement,

the controlling_expression is evaluated.– The value of the controlling_expression is compared

with the value succeeding each of the case statements.– Flow of control is transfer to the case statement with the

succeeding value equal to the value of the controlling_expression.

– If none of the values succeeding the case statements matches the value of controlling_expression, the flow of control is transferred to the default statement.

– break statement at the end of each case block transfers the flow of control to the first statement after the switch structure.

49

Example: switch<HTML>

<HEAD>

<TITLE>switch in JavaScript </TITLE>

<SCRIPT LANGUAGE="JavaScript">

var Operand1Str;

var Operand2Str;

var Operand1;

var Operand2;

var Operation;

var Problem;

var Answer;

Operand1Str = window.prompt("Enter operand1","0");

Operation = window.prompt("Enter operation\n+ - / *");

Operand2Str = window.prompt("Enter operand2","0");

Operand1 = parseFloat(Operand1Str);

Operand2 = parseFloat(Operand2Str);

document.write(Operand1 + Operation +Operand2);

Problem = 0;

50

Example: switch(Contd.)switch(Operation)

{

case "+":

Answer = Operand1 + Operand2;

break;

case "-":

Answer = Operand1 - Operand2;

break;

case "/":

if (Operand2 == 0.0)

{

document.write("<STRONG>=Infinity</STRONG><BR>");

Problem = 1;

}

else

Answer = Operand1/Operand2;

break;

51

case "*":

Answer = Operand1 * Operand2;

break;

default:

Problem = 1;

document.write("<STRONG><EM>Invalid Operation</EM></STRONG><BR>");

}

if (!Problem)

document.write("=" + Answer + "<BR>");

</SCRIPT>

</HEAD>

<BODY>

<P>Prepared by Omar Bashir</P>

</BODY>

</HTML>

Example: switch(Contd.)

52

The do-while Repetition Structure

• The do-while structure tests the loop continuation condition after the loop body is performed.– Loop body is performed at least once.

• Syntax– do

{statement;}

while (condition);– statement is executed till condition is true.

53

do-while Example<HTML>

<HEAD>

<TITLE>JavaScript Examples</TITLE>

<SCRIPT LANGUAGE='Javascript'>

var HeadingNumber;

HeadingNumber = 1;

do

{

document.write("<H"+HeadingNumber+">Heading "+HeadingNumber);

document.write("</H><BR>");

HeadingNumber++;

}

while (HeadingNumber < 7);

</SCRIPT>

</HEAD>

<BODY>

<P>JavaScript Examples</P>

</BODY>

</HTML>

54

Logical Operators• Logical operators are used to form complex

logical expressions.– Simple logical expression

• Salary is less than 10000;

– Complex logical expression• Salary is less than 10000 OR Hours Worked are less than

10.

• Logical operations provided in Javascript– && : AND : expr1 && expr2: true when both are true

– || : OR : expr1 || expr2: true when any one is true

– ! : NOT : !expr1 : : true when expr1 is false

55

Logical Operators -

Exam

ples

• &&– (Salary <= 10000) && (HoursWorked <=10)

• Salary = 5000, HoursWorked = 15 : FALSE• Salary = 15000, HoursWorked = 5 : FALSE• Salary = 15000, HoursWorked = 15 : FALSE• Salary = 5000, HoursWorked = 5 : TRUE

• ||– (Salary <= 10000) || (HoursWorked <=10)

• Salary = 5000, HoursWorked = 15 : TRUE• Salary = 15000, HoursWorked = 5 : TRUE• Salary = 15000, HoursWorked = 15 : FALSE• Salary = 5000, HoursWorked = 5 : TRUE

• !– !(Salary <= 10000)

• Salary = 5000 : FALSE• Salary = 15000 : TRUE

56

<HTML>

<HEAD>

<TITLE> Logical Operations </TITLE>

<SCRIPT LANGUAGE="Javascript">

var SalaryStr;

var Salary;

var IncomeTax;

var NetIncome;

document.write("<H1>Tax Calculator</H1><BR>");

SalaryStr = window.prompt("Enter your salary","0");

Salary = parseFloat(SalaryStr);

if (Salary <= 5000)

IncomeTax = Salary * 0.05;

else

Logical Operators -

Exam

ples

57

Logical Operators –

Exam

ple (C

on

td.)

{

if ((Salary > 5000) && (Salary <=10000))

IncomeTax = Salary * 0.1;

else

IncomeTax = Salary * 0.15;

}

NetIncome = Salary - IncomeTax;

document.write("Salary = " + Salary + "<BR>");

document.write("Income Tax = " + IncomeTax + "<BR>");

document.write("Net Income = " + NetIncome + "<BR>");

</SCRIPT>

</HEAD>

<BODY>

<P><EM>Javascript control structures</EM></P>

</BODY>

</HTML>


Recommended