JavaScript for QA

Engineers by David Shtern

David Shtern, Ph.D., © 2008, All Rights

Reserved.

JavaScript Class Objectives

• Understand basics of JavaScript

• Learn where JavaScript is used

• Be able to answer interview questions

• Be able to test web pages containing

JavaScript

David Shtern, Ph.D., © 2008, All Rights

Reserved.

JS – what is it?

JavaScript is THE scripting language of the Web.

JavaScript is used in many Web pages adding functionality, form validation, browser detection and much more.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

JS – what is it?

JavaScript was designed with the aim to add interactivity to HTML pages

JavaScript is a scripting language -lightweight programming language

Most common place to find JavaScript embedded in HTML pages

JavaScript is an interpreted language (means that scripts execute without preliminary compilation); interpreter is located in your browser

JavaScript is free

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Prerequisites – HTML and OOP

OOP, or Object Oriented Programming – is a technique allowing programmers to reuse and simplify the code.

For simplicity reasons we take into consideration a case of a bank, which have some branches.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Banks

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Bank branches

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Bank operations

For simplicity reasons we assume that there are only four operations performed by bank:

Deposit (checks and cash)

ATM (cash out only)

Loan application acceptance

Issuance of Consumer credit

David Shtern, Ph.D., © 2008, All Rights

Reserved.

OOP

If we allow each bank branch to develop its own software it will be the end of banking industry.

We need to set up standards and rigorously follow them to make sure business rules and regulations are observed by all branches.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Head office and branches

$

Bank

$

Bank

David Shtern, Ph.D., © 2008, All Rights

Reserved.

$

Bank

Lead letter printing

© http://www.hno.harvard.edu/gazette/2002/05.16/14-bowandarrow.html

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Lead letter printing

© http://www.hno.harvard.edu/gazette/2002/05.16/14-bowandarrow.html

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Lead letter printing in software

We create a matrix, with all functions, business rules etc, and simply make copies for each bank branch.

If central bank office authorize a bank loan to

Doe Joe, a following command is executed:

Nashwille.IssueLoan(12, 50,000);

Nashville branch gives customer Doe Joe (with ID

12) a 50,000 loan.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

OOP syntax

Nashwille.IssueLoan(12, 50,000);

IssueLoan () operation can be performed by any bank brunch. However, in our case it is executed by Nashville brunch.

IssueLoan() operation needs additional information

(parameters) in order to perform loan release

(customer ID, loan amount)

Each operation is ended with semicolon.

Central office cannot get access to cash registry of

Nashville brunch.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Variables

In computer programming a variable is a special value (also often called a reference) that has the property of being able to be associated with another value (or not). What is variable across time is the association. Creating or changing the association is called assignment.

Variables are usually named by an identifier

In the computing context, variable identifiers often consist of alphanumeric strings.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Variables - continued

Declaring a variable in JavaScript is easy: var d – declares (creates) variable named ‘d’ and does not assigns (associate) any value with it.

var dat = 1; var car12 = “Honda”;

In these cases we declare variables and at the same time associate values to them.

When we expect that the value of variable is not to be changed, we use const keyword, e.g.

const FREEZING_F = 32

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Variables

Regard a variable as a container which may store value(s),

Values may change upon assigning variable new value,

We can get value stored in variable by referring it,

Variable allow to separate assignment and value reading in time,

JavaScript supports variables.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Variables rules

Rules for JavaScript variable names:

Variable names in JavaScript are case sensitive ( z and Z are two different variables)

Variable names must begin with a letter or the underscore character

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Assignment operation

var x= 11; var city = “Odessa”;

Compare with this syntax, which is also OK: x= 11; city = “Odessa”;

JavaScript assumes that x and city are variables.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Variables scope

Local and global scope variables: var gl = 6; funcrion foo()

}

{ var l; var b = 7; document.write (“local var” + b+”<BR>”); document.write (“global var” + gl +”<BR>”);

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Variables in action

Create following document in left window. Then see how it looks in browser/right window:

<HTML>

<BODY>

<script type="text/javascript"> var car = “Mazda MPV"; var pi = 3.141592653589793; document.write("<h1>First js script</h1>"); document.write("<p>Hello World</p>"); document.write("<p>Bye</p>"); document.write(“Value of pi is: “ + pi); document.write(“<BR>My car is: “ +car);

</script>

</BODY>

</HTML>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

What JS can

JavaScript gives HTML designers a programming tool HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small

"snippets" of code into their HTML pages

JavaScript can put dynamic text into an HTML page A

JavaScript statement like this: document.write("<h1>" + name +

"</h1>") can write a variable text into an HTML page

JavaScript can react to events A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element

JavaScript can read and write HTML elements A JavaScript can read and change the content of an HTML element

David Shtern, Ph.D., © 2008, All Rights

Reserved.

What JS can

JavaScript can be used to validate data A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing and network to transfer this data

JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser

JavaScript can be used to create cookies - A

JavaScript can be used to store and retrieve information on the visitor's computer

David Shtern, Ph.D., © 2008, All Rights

Reserved.

JS in HTML documents

<HTML>

<HEAD>

</HEAD>

<BODY>

<SCRIPT TYPE="TEXT/JAVASCRIPT">

Some code here...

</SCRIPT>

</BODY>

Observe that JS code is in BODY part of the code.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

JS in HTML documents

<HTML>

<HEAD>

<SCRIPT TYPE="TEXT/JAVASCRIPT">

Some code here...

</SCRIPT>

</HEAD>

<BODY>

Some HTML code here…

</BODY>

JavaScript is executed as soon as the page is loaded!

David Shtern, Ph.D., © 2008, All Rights

Reserved.

External JavaScript file

JavaScript code is in external file which we reference:

<HTML>

<HEAD>

<SCRIPTSRC="XXX.JS">

</SCRIPT>

</HEAD>

<BODY>

</BODY>

</HTML>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

JavaScript basics

JavaScript Statement.

A JavaScript statement is a command to the browser.

The purpose of the command is to tell the browser what to do.

The text of the command is written in JavaScript code; the command is executed by browser.

Always terminate statement with “;” though it is not required by JavaScript.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

JavaScript basics

JavaScript code (or just JavaScript) is a sequence of JavaScript statements.

Each statement is executed by the browser in order they are written.

Groups of JavaScript statements can be grouped in blocks. Blocks start with a left curly bracket { and ends with a right curly bracket }.

The purpose of a block is to make the sequence of statements execute together.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Our First JavaScript

Open Notepad and type following text:

<HTML>

<HEAD>

<TITLE> My JS example

</TITLE>

</HEAD>

<BODY>

<script type="text/javascript"> document.write("<h1>First js script</h1>"); document.write("<p>Hello World</p>"); document.write("<p>Bye</p>");

</script>

</BODY>

</HTML>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Saving file

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Opening file in browser

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Writing text to browser

Lesson learned:

JavaScript can write text into browser window.

If we write HTML code to browser then browser, in addition to displaying text provided by JavaScript, also interprets

HTML code.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

JavaScript

Navigate to: http://www.w3schools.com/js/tryit.

asp?filename=tryjs_statements

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Commenting JS with //

Only JS code part is shown:

<script type="text/javascript">

// this writes document title in window document.write("<h1>First JavaScript</h1>");

// this writes regular statement document.write("<p>Hello World</p>");

// saying Bye to World: document.write("<p>Bye</p>");

</script>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Multi-line comments

Try following code (modify existing document):

<HTML>

<HEAD>

<TITLE> this document is created by (your name here)

</TITLE>

</HEAD>

<BODY>

<script type="text/javascript">

/* document.write("<h1>First js script</h1>"); document.write("<p>Hello World</p>"); document.write("<p>Bye</p>"); */

</script>

</BODY>

</HTML>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

JS Lesson 2

Lesson learned – JavaScript allows to store information in variables. Values stored in variables are available at any time. Variables can be concatenated with strings and other variables.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

JavaScript Operators

Operator Description and Example

Addition x=y+2

Subtraction x=y-2

Multiplication x=y*2x

Division x=y/2x

Modulus (division remainder) x=y%2

Increment x=++y (compare x=y++)

Decrement x=--y (pre-decrement)

David Shtern, Ph.D., © 2008, All Rights

Reserved.

JavaScript Operators - continued

Operator Description and Example

Equality x==y

Not equal x!=y

Greater than x>y

Greater or equal x>=y

And && or ||

Not !

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Assignment Operators

Assignment operators are used to assign values to JavaScript variables.

Given that x=10 and y=5 , expressions below illustrate assignment operators: x+=y equivalent to x=x+y // new value is 15 x/=y equivalent to x = x/y // new value is 2

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Manipulation with variables

String concatenation is achieved using + operator. To combine two strings:

<script type="text/javascript"> var txt1="What a very"; var txt2=“ nice day"; var txt3=txt1+txt2; document.write (txt3);

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Addition operation

Try this:

<script = javascript> x=5+5; document.write(x); x="5"+"5"; document.write(x); x=5+"5"; document.write(x); x="5"+5; document.write(x);

</script>

Result: Adding number and a string result is always a string.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Operators. Continued

== is equal to x==8

=== is exactly equal to (value and type) x==5 is true x==="5" is false! x!=8 is true (if x is not 8) - less than 8 or is greater than 8

Greater or equal to x>=8

<=is less than or equal

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Logical operations

Logical operation allow application to make a decision which of two (or more) execution paths to take.

In interactive web pages one hardily can avoid using conditional statements.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Logical Operator in action

This question is taken from DMV web page:

David Shtern, Ph.D., © 2008, All Rights

Reserved.

JS smart decisions

Correct answer is M2. However how can we “educate” our HTML code/JavaScript to pick up correct answer “on fly” – without sending answer to server first and also be able to answer more complicated questions?

David Shtern, Ph.D., © 2008, All Rights

Reserved.

DMV requirements/(loose)

Software specifications

From DMV website:

To apply for a motorcycle Class M1 or M2 permit, you will need to:

Be at least 15 ½ years of age

Complete application form DL 44 (An original DL 44 form must be submitted. Copies obtained by Xeroxing, faxing, or other methods will not be accepted.)

Have your parents’ or guardians’ signatures on the application form

DL 44

If you are under 21 , you must provide a completion certificate from the motorcycle rider training course .

If you are over 21 , you may complete and provide the completion certificate from the motorcycle rider training course OR schedule an appointment at DMV to take the motorcycle driving test.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Checking eligibility for Motorcycle course/requirements implementation

<script type="text/javascript"> var students_age = 15.5; // hard-coded value var txt1="Not entitled"; // constant

{ var txt2="Allowed"; // constant if (students_age <15.5) // logical condition, answer to which is always ‘Yes’ or

‘No’

} document.write (txt1); else

{ document.write (txt2);

}

</script>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Checking eligibility for Motorcycle course – improved.

<script type="text/javascript"> var students_age = 15.5;

} if (students_age<15.5)

{ document.write ("sorry, you cannot take any courses or take exam.")

{ else if (students_age>=15.5 && students_age<16)

} else document.write ("Come to DMV with your legal guardian");

{ document.write ("No restrictions. Welcome to DMV");

}

</script>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Checking eligibility for Motorcycle course – adding a function and input field.

<HTML>

<HEAD></HEAD>

<BODY> <FORM id="form1" runat="server">

<P><input id="Text1" type="text" /></P>

<script type="text/javascript"> function CheckEligibility(args)

{ var students_age = Text1.value; //= 15.5; if (students_age<15.5)

{ document.write ("sorry, you cannot take any courses.")

{

}

{ else if (students_age>=15.5 && students_age<16) document.write ("Come with your legal guardian");

} else document.write ("No restrictions. Welcome to DMV");

}

}

</script>

</BODY></HTML>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Checking eligibility for Motorcycle course – event handler and function call.

Create separate HTML document and place the code there:

<HTML>

<HEAD></HEAD><BODY><FORM id="form1" runat="server">

<P><input id="Textone" type="text" OnChange="CheckEligibility(this) "/></P>

<script type="text/javascript">

{ function CheckEligibility(args) var students_age = args.value;

{ if (students_age<15.5)

{ document.write (“<H1>sorry, you cannot take any courses!</H1>")

} else if (students_age>=15.5 && students_age<16) document.write ("Come with your legal guardian");

}

{ else document.write ("No restrictions. Welcome to DMV");

}

}

</script></BODY></HTML>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Checking eligibility for Motorcycle course – with push button.

Create separate HTML document and place the code there:

<HTML>

<HEAD><script type="text/javascript"> function CheckEligibility()

{ var age =document.formOne; stuage = age.ageinput.value; if (stuage<15.5)

{ document.write ("sorry, you cannot take any courses.")

} else if (stuage>=15.5 && stuage<16)

{ document.write ("Come with your legal guardian");

} else

{ document.write ("No restrictions. Welcome to DMV");

} return true;

}

</script></HEAD>

<BODY><FORM id="forma" name="formOne" runat="server" onsubmit="return CheckEligibility()">

<P><input id="Textone" name ="ageinput" type="text" size="20"></P>

<P><input type="submit" value="Check Eligibility"></P>

</BODY></HTML>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Exercise

Modify existing code so page prompts you to input your name. After name <full name> is submitted a greeting appears on the page: “Hello <full name>!” where <full name> is text user puts in text box.

Modify existing code so there are two text fields on the page. Upon entering numbers in these fields and clicking push button their sum shall be shown

Modify existing code so page prompts you to input radius. After radius value is submitted circumference is calculated.

(http://www.gtalbot.org/BrowserBugsSection/MSIE7Bugs

/JSConstKeyword.html)

Advanced. Write a code which takes input temperature in F and converts it to C.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Randomness

Sometimes you need to get random numbers. JavaScript allows you to access

Math library, which contains function

‘random’.

To get random number use construct: var r=Math.random();

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Randomness

<HTML>

<HEAD><script type="text/javascript">

{ function generate_random() var rndm=Math.random(); document.write( rndm*1000);

}

</script></HEAD>

<BODY><FORM id="forma" name="formOne" runat="server" onsubmit="return generate_random()">

<P><input type="submit" value="Generate random number"></P>

</BODY></HTML>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Randomness – with rounding

Random number generation produce floating numbers.

What if we like to have integers? It is possible to round up floating number using function round();

Modify existing code:

{ function CheckEligibility() var rndm = Math.random(); var rounded = Math.round(1000*rndm);

} document.write (rounded);

</script>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Exercise

1.

2.

3.

Modify existing code so script prints random ZIP code

Modify existing code so random SSN number is printed

Modify existing code so random phone number is printed

56

Repeating operation

What we like to do is to generate random number repeatedly.

When some operation is to be repeated many time it is time to implement loops.

Loops is a cycle, in which operation(s) repeated many times.

We can control loops by specifying its starting and ending conditions and also number of cycles.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Loops

Create HTML document. Test it.

<html>

<HEAD>

</HEAD>

<body>

<script type="text/javascript">

{ for (i=0;i<=5; i++)

} document.write ("Current value of iterator " + i); document.write ("<BR>");

</script>

</body>

</html>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Loops

for (i = 0; i <= 5; i++){

// body of the loop

} document.write("The number is " + i) document.write("<br>") i=0 this is loops initial condition i<= 5 this is loop end condition i++ value of I is incremented with each iteration

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Generating random numbers in loop

<HTML>

<HEAD></HEAD>

<body>

<h1>Random Data Generation</h1>

<form name="form1">

{

<script type="text/javascript"> function Foo()

{ for (i=0; i<20; i++) rndm = Math.random(); document.write(rndm +"<BR>");

}

}

</script>

<br>

<input type="button" name="CheckButton" value="Randoms" onClick="Foo()">

</form></body></HTML>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

While loop

While loop differs from “for” loop in a way that we do not define start condition; there is no iterator defined.

While loop starts when logical condition is evaluated to ‘true’ and is running while the condition keeps evaluating to true.

While loop can be terminated within the loop.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

While loop

<html>

<body>

<script type="text/javascript"> i = 0 while (i <= 5){ document.write("The number is " + i) document.write("<br>") i++

}

</script>

</body>

</html>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

While loop

If we do not increment variable i in the body of while loop, the loop will never terminate.

Browser will keep printing strings in the window until all computer resources are consumed.

This is a case of eternal loop which is never been useful other that illustrating bad programming design.

while (i <= 5){ document.write("The number is " + i) document.write("<br>") i++

}

</script>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

While loop. Modified.

<html><body>

<script type="text/javascript"> i = 0

{ while (2) // this condition is always true document.write("The number is " + i) document.write("<br>") if (++i>20) // preincrement. Try this version too i++. Any difference?

}

}

{ break;

</script></body></html>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Sleep function

There is no sleep() function in JavaScript found in many other languages.

There are workarounds though, like

}

} function pause(millisecs)

{ var now = new Date(); var exitTime = now.getTime() + millisecs; while(true)

{ now = new Date(); if(now.getTime() > exitTime) return;

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Alert Box

Try following code:

<HTML>

<HEAD>

</HEAD>

<BODY>

<script type="text/javascript">

{ function disp_alert()

} alert("I am an alert box!");

</script>

<input type="button" onclick="disp_alert()" value="Display alert box" />

</BODY>

</HTML>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Expected result

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Exercise

Modify one of existing scripts so:

User enters credit card number in text box and presses

Submit button. If number of digits not equal to 16 an alert box is shown.

HTML part of the code:

<BODY><FORM id="forma" name="formOne" runat="server" onsubmit="return CheckCC()">

<P><input id="Textone" name =“ccinput" type="text" size="20"></P>

<P><input type="submit" value="Check CC"></P>

</BODY></HTML>

68

Operations with Strings - Changing

Case

<HTML>

<HEAD>

<script type="text/javascript"> function toupper_string()

{ var str = myForm.text1.value; str = str.toUpperCase(); // try also toLower()

} return str;

</script>

</HEAD>

<form name="myForm">

Reversing string: <input type="text" name="text1" size="50">

<br><br>

<input type="button" value="Change to Upper" onClick="myForm.text1.value=toupper_string()">

</form></body></html>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Operations with Strings Counting

Letters

{

<HTML>

<HEAD>

<script type="text/javascript"> function count_string() var str = myForm.text1.value; return str.length;

}

</script>

</HEAD>

<form name="myForm">

Reversing string: <input type="text" name="text1" size="50">

<br>

Characters in string: <input type="text" name="counter" size="12">

<br>

<input type="button" value="Change to Upper" onClick="myForm.counter.value=count_string()">

</form>

</body>

</html>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Counting Letters - automatically

<HTML>

<HEAD>

<script type="text/javascript"> function count_string()

{ var str = myForm.text1.value;

} return str.length;

</script>

</HEAD><BODY>

<form name="myForm">

Reversing string: <input type="text" name="text1" size="50" onkeyup="myForm.counter.value=count_string()">

<br>

Characters in string: <input type="text" name="counter" size="12" >

<br>

<input type="button" value="Change to Upper" onClick="myForm.counter.value=count_string()">

</form></body></html>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Substring

<HTML><HEAD>

<script type="text/javascript">

{ function trim_string() var str = myForm.text1.value;

} var offset = myForm.offsett.value; var charn = myForm.charnum.value; str = str.substr(offset,charn); return str;

</script>

</HEAD>

<form name="myForm">

Enter text: <input type="text" name="text1" size="50" >

<br>

Enter start position: <input type="text" name="offsett" size="12">

<br>

Enter number of chars to trim: <input type="text" name="charnum" size="12">

<BR>

<input type="button" value="Trim String" onClick="myForm.text1.value=trim_string()">

<br>

</form></body></html>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Slicing Strings

string.slice(num1, num2) string.slice(num)

The slice() method returns the characters between the indexed positions num1 and num2.The first character is in position 0.If num2 is a negative number, the string counts from the end of the string to end the slice.If passing a single index, the method will return all characters until the end of the string.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Arrays

New data structure - Array single variable single value

Compare: var temp = 12 single variable multiple values var tempArray = (“orange”,

“apple”,

“peach” );

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Arrays

str.split(<pattern>) function returns not a single value, but list of values. It is said that split returns an ARRAY, or list.

E.g.: var tempArray = str.split(' ').sort();

We split (cut) string str into several peaces.

We cut on empty spaces (specified by ‘ ‘).

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Arrays

Alternatively, we can declare array and place some words into it:

E.g. (HTML header and body tags omitted):

<script type="text/javascript"> var nameArray = new Array(“Element 1",“elemen t 2",“element 3",“arr_el 4",“this 5",“finally 6") for (i=0; i<nameArray.length; i++){ document.write(nameArray[i] + "<br>")

} // iterating through loop

</script></body></html>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Arrays

Declaring an array nameArray and populating it at the same time (initializing): var nameArray = new Array(“Element 1",“element 2",“elem ent 3",“arr_el 4",“this 5",“finally 6");

We can access each element of the array using its index.

Array index starts at 0, so nameArray[0] gives us value of first element.

} for (i=0; i<nameArray.length; i++){ document.write(nameArray[i] + "<br>")

Array.length function tells us (returns integer) how many elements are in the array.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Arrays. Splitting string.

<HTML><HEAD></HEAD><body>

<h1>Word count</h1>

<form name="formOne">

<script type="text/javascript">

{ function Foo() var myStr = formOne.Results.value; var tempArray = myStr.split(' '); return tempArray.length;

}

</script>

<br>

You entered <input type="text" name="NameLength"> words.<BR>

<TEXTAREA NAME="Results" ROWS=10 COLS=80></TEXTAREA><BR>

<input type="button" name="CheckButton" value="Calculate" onClick="formOne.NameLength.value=Foo()">

&nbsp;</form></body></HTML>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Exercise

Modify code from previous slide so

JavaScript calculates how many letters

(instead of words) are in the string.

Advanced. Modify code from previous slide so JavaScript calculates how many times letter a appears in the string.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Arrays. Reversing string

<HTML><HEAD></HEAD><BODY><H1>Reversing Words</H1><form name="formOne">

<script type="text/javascript">

{ function Foo() var reversedStr = ''; var myStr = formOne.Results.value; var tempArray = myStr.split('');

{ for (i=tempArray.length-1; i>=0; i--) reversedStr += tempArray[i];

} return reversedStr;

}

</script><BR><TEXTAREA NAME="Results" ROWS=10 COLS=80></TEXTAREA>

<BR>

<input type="button" name="CheckButton" value="Reverse" onClick="formOne.Results.value=Foo()">

&nbsp;</form></body></HTML>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Arrays. Validating input – part 1

<HTML><HEAD></HEAD><BODY><H1>Validating Input</H1>

<form name="formOne"><script type="text/javascript">

{ function Foo() var myStr = formOne.text1.value; myArray = myStr.split('');

{ for (j=0; j<myArray.length; j++) if ((myArray[j].charCodeAt()<48)||(myArray[j].charCodeAt()>57))

{ alert("Only numeric values are accepted for age!"); break;

{

}

} if (myStr.length > 3) alert("Age value cannot exceed three digits!");

}

} return;

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Arrays. Validating input – part 2

Rest of the code:

</script>

<br> Your age:

<input type="text" name="text1" size=“10">

<BR>

<input type="button" name="CheckButton" value="Register" onClick="Foo()">

&nbsp;

</FORM>

</BODY>

</HTML>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Events

onAbort ( ) onActivate ( ) onAfterPrint ( ) onAfterUpdate

( ) onBeforeActivate ( ) onBeforeCopy ( ) onBeforeCut ( ) onBeforeDeactivate ( ) onBeforeEditFocus ( ) onBeforePaste ( ) onBeforePrint ( ) onBeforeUnload ( ) onBeforeUpdate ( ) onBlur ( ) onBounce ( ) onCellChange ( ) onChange ( ) onClick ( ) on

ContextMenu ( ) onControlSelect ( ) onCopy ( ) onCut (

) onDataAvailable ( ) onDatasetChange ( ) onDatasetC omplete ( ) onDblClick ( ) onDeactivate ( ) onDrag ( ) on

DragEnd ( ) onDragEnter ( ) onSneeze () ;)

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Combo Box selection

<html>

<head>

<script type="text/javascript"> function put(){ txt=document.forms[0].myList.options[document.forms[0].myList.selectedIndex].text

document.forms[0].favorite.value=txt

}

</script></head><body><form>

Select your favorite car model:

<select name="myList" onchange="put()">

<option>BMW</option>

<option>Mercedes</option>

<option>Acura</option>

<option>Buick</option>

<option>Audi</option>

<option>Caddy</option>

</select>

<br><br>

Your favorite car indeed is: <input type="text" name="favorite" size="20">

</form></body></html>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Select statement

Modify previous example so code looks like: txt=document.forms[0].myList.options[document.forms[0].myList.selectedIndex].text

switch(txt){ case "BMW" : phrase = "Ah, driving Beemer, heh?"; break; case "Mercedes" : phrase = "You too?"; break; case "Acura" : phrase = "Not bad!"; break; case "Buick" : phrase = "Got enough room?"; break; case "Audi" : phrase = "German car too"; break; case "Audi" : phrase = "Cool dude!"; break; default : phrase = "Really bicycle?"; break;

} document.forms[0].favorite.value=phrase;

David Shtern, Ph.D., © 2008, All Rights

Reserved.

How Select statement works

Modify previous example so code looks like: switch(txt){ // this is input case "BMW" : // this is one choice of many phrase = "Ah, driving Beemer, heh?"; break; // if choice is evaluated to true we make assignment and exit case "Mercedes" : phrase = "You too?"; break; default : // this is default value. If no choice is evaluated to true execution goes

// to default phrase = "Really bicycle?"; break;

} document.forms[0].favorite.value=phrase;

David Shtern, Ph.D., © 2008, All Rights

Reserved.

DateTime

<HTML>

<HEAD>

<script type="text/javascript"> function get_curr_date()

{ var myDate = new Date(); return myDate.toLocaleString();

}

</script>

</HEAD>

<body>

<h1>Getting current Date and Time</h1>

<form name="form1">

<input type="text" size=50 name="result"><BR>

<input type="button" name="CheckButton" value="Get current Date" onClick="document.form1.result.value ='' + get_curr_date()">

<br>

</form>

</body>

</HTML>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

DateTime

It is possible to retrieve parts of Date and Time, e.g. YEAR or MONTH.

There are methods getYear(), getDay(), getMonth(), getSeconds(). Value of YEAR is given as number of years from 1900, so to get current year add 1900:

<HTML>

<HEAD>

<script type="text/javascript"> function get_curr_date()

{ var myDate = new Date(); return myDate.getYear()+1900;

}

</script>

</HEAD>

<body>

<h1>Getting current Year</h1>

<form name="form1">

<input type="text" size=50 name="result"><BR>

<input type="button" name="CheckButton" value="Get current Year" onClick="document.form1.result.value

='' + get_curr_date()">

<br>

</form>

</body>

</HTML>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Using DateTime value

Last modified date:

<html>

<script language="JavaScript"> document.write("This document was last modified on ",document.lastModified);

</script>

</html>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Field validation.

<HTML><HEAD></HEAD><BODY><H1>Validating Fields</H1>

<form name="formOne"><script type="text/javascript">

{ function Foo() var myStr = formOne.text1.value;

}

{ if (myStr.length > 2) alert("First name shall not exceed 2 characters!");

} return;

</script>

<br> First name: <input type="text" name="text1" size="50">

<BR><input type="button" name="CheckButton" value="Register" onClick="Foo()">

&nbsp;</FORM></BODY></HTML>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Regular Expressions

1. Navigate to http://www.java2s.com/Code/JavaScript/D evelopment/RegularExpressionTester.htm

2. Copy code to NotePad. Save it as

Regex.html (type ‘All Files’)

3. Open Regex.html

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Regex tester

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Patterns – symbols with special meaning

\d stands for one digit

\d{n,m} stand for minimum n digits, maximum m

. Stands for any character, but newline

\s stands for space

\S stands for anything but space

\D stands for anything but digit

.* zero or more characters

.? One character

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Regular Expressions

\w Matches any word character (alphanumeric).

\W Matches any non-word character.

\s Matches any whitespace character (tab, newline, carriage return, form feed, vertical tab).

\S Matches any non-whitespace character.

[\b] Matches a backspace.

. Matches any character except a newline.

[...] Matches any one character within the brackets.

[^...] Matches any one character not within the brackets.

[x-y] Matches any character in the range of x to y.

[^x-y] Matches any character not in the range of x to y.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Regular Expressions

{x,y} Matches the previous item at least x times but not to exceed y times.

{x,} Matches the previous item at least x times.

{x} Matches the previous item exactly x times.

? Matches the previous item once or not at all.

+ Matches the previous item at least once.

* Matches the previous item any number of times or not at all.

| Matches the expression to the left or the right of the | character.

(...) Group everything inside parentheses into a subpattern.

\x Matches the same characters that resulted from the subpattern in group number x. Groups, which are designated with parentheses, are numbered from left to right.

^ Matches the beginning of the string or beginning of a line, in multiline matches.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Regular Expressions

$ Matches the end of the string or end of a line, in multi-line matches.

\b Matches the position between a word character and a non-word character.

\B Matches the position that is not between a word character and a non-word character.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Regex Exercise

Substitute phone number 123-4567 with (408)

555 5555

Substitute <hyphen.> with hyphen (-).

Susbstitute all capital letters with ‘A’

Substitute all ‘a’ articles with ‘the’

Find out if original string contains word digit

What following regex matches: .+?@.?+\ ....

Which regex can be used to match person first name?

David Shtern, Ph.D., © 2008, All Rights

Reserved.

String Substitution with Regex

string.replace(regexpression, replacestring)

The replace( ) method searches the string for the regular expression passed to the method.

If a match is found, the method returns a new string with that match replaced with the replacement string passed to the method.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Quantifiers and options

+ stands for one or more

* stands for zero or more characters

? stands for one character i – case insensitive g – global search m – search across multiple lines

David Shtern, Ph.D., © 2008, All Rights

Reserved.

User Screen properties

<html>

<head>

<script language="JavaScript1.2">

<!-function openWin(){ var myWin = open("", "","width=450,height=200"); myWin.document.write("The availHeight is: " + screen.availHeight + "<br>"); myWin.document.write("The availWidth is: " + screen.availWidth + "<br>"); myWin.document.write("The colorDepth is: " + screen.colorDepth + "<br>"); myWin.document.write("The height is: " + screen.height + "<br>"); myWin.document.write("The pixelDepth is: " + screen.pixelDepth + "<br>"); myWin.document.write("The width is: " + screen.width + "<br>"); myWin.document.close();

}

-->

</script>

</head>

<body>

<form name="myForm">

<input type=BUTTON value="Click to See Screen Properties" name="myButton" onClick="openWin()">

</form>

</body>

</html>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

OnMouseOver

<HTML>

<HEAD>

<TITLE>Using functions as event handlers</TITLE>

<SCRIPT LANGUAGE="JavaScript">

<!-function confirmLink() { alert("www.java2s.com") if(confirm("www.java2s.com?")) {

} window.location="http://www.java2s.com"

}

//-->

</SCRIPT>

</HEAD>

<BODY>

<H1>Using functions as event handlers</H1>

<P><A HREF="somewhere" onClick="return false" onMouseOver="confirmLink

()">Confirms whether you want to connect via this link.</A></P>

</BODY>

</HTML>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Hanging document properties

<html>

<head>

<title>properties_title</title>

<script language="JavaScript"> function function1() { document.title = "This is the new title ";

} function function2() { var n = document.title; alert(n);

}

</script></head>

<body>

<button onclick="function1();">Click here to change the title of this p age</button>

<button onclick="function2();">Click here to display the title of this p age</button>

</body></html>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Alert box with multi lines

<HTML>

<HEAD>

{

<SCRIPT type="text/javascript"> function disp_alert()

} alert("Hello again! This is line number one" + '\n' + "and here is line number two in alert box!");

</SCRIPT>

</HEAD>

<BODY>

<input type="button" onclick="disp_alert()" value="Display alert box" />

</BODY>

</HTML>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Confirmation message box

{

<html>

<head>

<script type="text/javascript"> function disp_confirm() var r=confirm("Press a button"); if (r==true)

}

{ document.write("You pressed OK!"); else

{

} document.write("You pressed Cancel!");

}

</script>

</head>

<body>

<input type="button" onclick="disp_confirm()" value="Display a confirm box" />

</body>

</html>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Prompt

<html><head>

<script type = "text/javascript"> function verify_password()

{ var docpwrd = prompt("Specify the password for this document:", "");

}

} if (docpwrd == "pwrdfile") { self.location = docpwrd + ".htm";

} else { alert("That is not the correct password.");

</script>

</head><body><form>

<input type="button" value="Open Password Protected File." name

="OpenFile" onClick="verify_password()"></p>

</form></body></html>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Our first interactive page

<html>

<head>

<script type="text/javascript"> function disp_prompt()

{ var name=prompt("Please enter your name",“Stirlitz"); if (name!=null && name!="")

}

{ document.write("Hello " + name + "! How are you today?");

{ else

Document.write (“We know who you are – FANTONAS”);

}

}

</script>

</head>

<body>

<input type="button" onclick="disp_prompt()" value="Display a prompt box" />

</body>

</html>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Interaction

Lesson – we achieved interaction with web pages, never possible before with web pages created with static languages, like

HTML and XML.

With JavaScript we can blow life into dead

HTML code and enjoy the result!

David Shtern, Ph.D., © 2008, All Rights

Reserved.

JavaScript - Detecting Browser

<html>

<HEAD>

<title>Browser infomation</title>

<SCRIPT> document.write('Browser: ' + navigator.appName); document.write('<br>Version: ' + navigator.appVersion); document.write('<br>Codename: ' + navigator.appCodeName); document.write('<br>Language: ' + navigator.language); document.write('<br>Platform: ' + navigator.platform);

</SCRIPT>

</HEAD>

<BODY>

</body></HTML>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Exception Handling

To catch JavaScript exception following constructs are used: try catch

Finally eval

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Exception Handling

<html>

<head>

<title>Try Catch Example</title>

<script type="text/javascript"> try { eval ("a -=++-% b");

} catch (oException) {

// bad statement alert("An exception is thrown.");

}

} finally { alert(“Exception was handled.");

</script></head><body></body></html>

David Shtern, Ph.D., © 2008, All Rights

Reserved.

JavaScript keywords

break case else New var finally return void catch for switch while continue function This with default if throw delete in do instanceof try typeof

David Shtern, Ph.D., © 2008, All Rights

Reserved.

<SCRIPT> tag attribute

The HTML 4 specification standardizes the < script > tag, but it deprecates the language attribute because there is no standard set of names for scripting languages.

Instead, the specification prefers the use of a type attribute that specifies the scripting language as a MIME type. Thus, in theory, the preferred way to embed a

JavaScript script is with a tag that looks like this:

< script type=" text/javascript "> In practice, the language attribute is still better supported than this new type attribute.

112

JS attribute

The HTML 4 specification also defines a standard (and useful) way to specify the default scripting language for an entire HTML file. If JavaScript is the only scripting language in a file, simply including the following line in the <head> of the document is enough:

<meta http-equiv="ContentScript -Type" content=" text/javascript "> Then we can safely use

JavaScript scripts without specifying the language or type attributes.

However!

113

JS attribute

Since JavaScript is the default scripting language, there is no need to use the language attribute to specify the language in which a script is written. However, there is an important secondary purpose for this attribute: it can also be used to specify what version of JavaScript is required to interpret a script . When you specify the language="JavaScript" attribute for a script , any

JavaScript-enabled browser will run the script . In cases, when script uses the exception-handling features of

JavaScript 1.5 it might be a problem.

114

JS attribute

To avoid syntax errors in browsers that do not support this version of the language embedding script with this tag is preferred:

< script language="JavaScript1.5"> If you do this, only browsers that support JavaScript 1.5 (and its exceptionhandling features) will run the script ; any others will ignore it.

115

INTERVIEW QUESTIONS 1

Q. What are JavaScript data types?

A Number, String, Boolean, Function, Object, Null,

Undefined.

Q What boolean operators does JavaScript support?

- &&, || and !

Q What does "1"+2+4 evaluate to?

- Since 1 is a string, everything evaluated to string, so the result is 124.

Q How about 2+5+"8"?

- Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the result.

David Shtern, Ph.D., © 2008, All Rights

Reserved.

INTERVIEW QUESTIONS 1

Javascript Interview Questions

1. What is JavaScript?

JavaScript is a platform-independent,event-driven, interpreted client-side scripting and programming language developed by Netscape Communications Corp. and Sun

Microsystems.

2.How to read and write a file using javascript?

I/O operations like reading or writing a file is not possible with client-side javascript.

However , this can be done by coding a Java applet that reads files for the script.

3.How to detect the operating system on the client machine?

In order to detect the operating system on the client machine, the navigator.appVersion string

(property) should be used.

What should appear at the very end of your JavaScript? The </script LANGUAGE=”JavaScript”> tag

David Shtern, Ph.D., © 2008, All Rights

Reserved.

JavaScript

function Finish()

{ return ‘end’;

}

David Shtern, Ph.D., © 2008, All Rights

Reserved.

Interview with Brendan Eich

http://www.infoworld.com/archives/emailPrin t.jsp?R=printThis&A=/article/08/06/23/eich

-javascript-interview_1.html

David Shtern, Ph.D., © 2008, All Rights

Reserved.