4 JavaScript
4 JavaScript
JavaScript
Hieu Dinh Vo
Outline
Introduction
Variables
Flow control statements
Objects
Events
Forms
Scripts
Client side
Run on client computer
Can be seen by users (Right mouse -> View
source)
Server side
Run on server
Users only see the output
What is JavaScript?
A programming language
A client-side script language, executed by Web
browsers
An interpreted language
Not Java
Enable JavaScript-Firefox
Enable JavaScript - IE
Enable JavaScript-Chrome
11
13
More examples
Use XHTML tags with JavaScript
Use CSS
window object
alert()
prompt()
14
Comments
Single line: //comments
Multiple lines: /* comments */
15
16
17
Variables
age
uname
22
USTH
Identifiers
Combination of letters, digits, underscores,
and dollar signs
Must begin with a character, dollar sign, or
underscore: name, _name, $name
Case-sensitive: name vs. Name vs. naMe
Must not be a keyword
19
JavaScript keywords
break
case
catch
continue
debugger
default
delete
do
else
finally
for
function
if
in
instanceof
new
return
switch
this
throw
try
typeof
var
void
while
with
20
String
21
Special Characters
Escape Sequences
Character Represented
\b
Backspace
\f
Form feed
\n
New line
\r
Carriage return
\t
Tab
Single quote
Double quote
\\
Backslash
\xNN
22
Convert to Strings
var num_value = 35.00;
var string_value = "This is a number:" + num_value;
var strValue = "4" + 3 + 1;
var strValueTwo = 4 + 3 + "1";
var firstResult = "35" - 3;
var str=String(value);
23
Boolean Type
var isMarried = true;
var hasChildren = false;
var someValue = 0;
var someBool = Boolean(someValue) // evaluates to false
var strValue = "1";
var numValue = 0;
var boolValue = !!strValue; // converts "1" to a true
boolValue = !!numValue; // converts 0 to false
24
NaN
NaN: Not a Number
var nValue = 1.0;
if (nValue == 'one' ) // false, the second operand is NaN
27
Assignment Statement
nValue = 35.00;
nValue = nValue + 35.00;
nValue = someFunction();
var firstName = lastName = middleName = "";
var nValue1,nValue2 = 3;
var nValue1=3, nValue2=4, nValue3=5;
nValue += 3.0;
28
Arithmetic Operators
Binary arithmetic operators: +, -, *, /, %
Unary arithmetic operators: -, ++, -var v = 3.0;
var v2 = ++v;
var v3 = v++;
29
Conditional Statements
if (condition) {
statements;
}
if (condition) {
statements;
} else {
statements;
}
30
Conditional Statements
If students grade is greater than or equal to 60
Print Passed
if ( studentGrade >= 60 )
document.writeln( "Passed" );
31
Conditional Statements
if ( studentGrade >= 60 )
document.writeln( "Passed" );
else
document.writeln( "Failed" );
document.writeln( studentGrade >= 60 ? "Passed" : "Failed" );
32
switch Statement
switch (expression) {
case firstlabel:
statements;
break;
case secondlabel:
statements;
break;
...
case lastlabel:
statements;
break;
default:
statements;
}
var country=;
switch (code) {
case 84:
country=Vietnam;
break;
case 1:
country=US;
break;
case 44:
country=UK;
break;
default:
country=Somewhere;
}
33
34
35
dowhile Loop
do {
strValue+=nValue;
nValue++;
} while (nValue <= 10)
36
for Loops
for (initial value; condition; update)
{
statements;
}
var s=0;
for (var i=10; i<100;i++){
if(i%2==0)
s=s+i;
}
37
JavaScript Objects
Boolean
Number
String
Date
Math
document
window
38
Number Object
Number.MAX_VALUE
The maximum number representation in JavaScript
Number.MIN_VALUE
The smallest positive number representation in
JavaScript
Number.NaN
Represents Not-a-Number
Number.NEGATIVE_INFINITY
Represents negative infinity
Number.POSITIVE_INFINITY
Represents infinity
39
String Object
Instantiate: var sObject = new String("Sample
string");
Some representative methods/properties
length
charAt, charCodeAt
indexOf
concat
substr
toLowerCase, toUpperCase
40
Methods of Strings
charAt( index): Returns a string containing the character at
the specified index.
concat( string): Concatenates its argument to the end of
the string that invokes the method.
indexOf(substring, index): Searches for the first occurrence
of substring starting from position index in the string that
invokes the method.
substr(start, length): Returns a string containing length
characters starting from index start in the source string.
substring(start, end): Returns a string containing the
characters from index start up to but not including index
end in the source string.
toLowerCase(): Returns a string in which all uppercase
letters are converted to lowercase letters.
41
Date Object
Instantiate
var dtNow = new Date();
var dtMilliseconds = new Date(5999000920);
var newDate = new Date("March 12, 1980 12:20:25");
Methods
getFullYear: The four-digit year
getHours: The hours component of the date/time
getMilliseconds: The milliseconds component of the
date/time
getMinutes: The minutes component of the date/time
toString: Outputs the string in local time
42
Math Object
Properties
PI: value of Pi
SQRT1_2: square root of 1/2
SQRT2: The square root of 2
Methods
Math.sin(x)
Math.cos(x)
Math.tan(x)
43
document Object
getElementById(id)
Returns the DOM node representing the XHTML
element whose id attribute matches id.
write(string)
Writes the string to the XHTML document as XHTML
code.
writeln(string)
Writes the string to the XHTML document as XHTML
code and adds a newline character at the end.
cookie
A string containing the values of all the cookies stored
on the users computer for the current document
44
window Object
Presents the window of Web browser
Properties
window.document: This property contains the document object
representing the document currently inside the window.
window.closed: set to true if the window is closed, and false if it is not.
Methods
open(url, name, options) Creates a new window with the URL of the
window set to url, the name set to name to refer to it in the script, and
the visible features set by the string passed in as option.
prompt(prompt, default) Displays a dialog box asking the user for
input.
close() Closes the current window and deletes its object from memory.
focus() This method gives focus to the window (i.e., puts the window
in the foreground, on top of any other open browser windows).
blur() This method takes focus away from the window
45
Arrays
var newArray = new Array('one','two');
var newArray = ['one','two'];
Multi-dimentional array
var threedPoints = new Array();
threedPoints[0] = new Array(1.2,3.33,2.0);
threedPoints[1] = new Array(5.3,5.5,5.5);
threedPoints[2] = new Array(6.4,2.2,1.9);
46
Functions
function functionname (param1, param2, ..., paramn) {
function statements
}
function sayHi(toWhom) {
alert("Hi " + toWhom);
}
sayHi(Tom);
47
Anonymous Functions
var variable = new Function ("param1", "param2", ... , "paramn", "function body");
var fcn=new Function("a", "b", "c","var g=a; if (g<b) g=b; if(g<c) g=c; return g");
s=fcn(7, 4, 6);
49
Function Literals
var func = function (params) {
statements;
}
var func = function (x, y) {
return x * y;
}
alert(func(3,3));
50
Events
Events allow scripts to respond to a user who
is moving the mouse, entering form data or
pressing keys, etc
Events and event handling help make web
applications more responsive, dynamic and
interactive
Events must be registered for handling
51
Inline Registration
<head>
<script type="text/javascript">
function eventHandler(){
window.alert("Hello");
}
</script>
</head>
<body>
<h1 onclick=eventHandler()">JavaScript</h1>
</body>
52
53
Popular Events
onload: fires whenever an element finishes
loading successfully
onmousemove: fires repeatedly whenever the
user moves the mouse over the web page
onmouseover: fires when the mouse cursor
moves into an element
onmouseout: fires when the mouse cursor
moves leaves the element
54
Forms
55
Forms
<form name="signin">
Username: <input type="text" name="email"/> <br/>
Password: <input type="password" name="passwd"/> <br/>
<input type="reset" name="reset" value="Reset"/>
<input type="submit" name="submit" value="Submit"/>
</form>
56
Form Elements
Text field: a box users can used to provide
one-line text data
Username: <input type="text" name=username" />
57
Form Elements
Password field: defines a password field
Password: <input type="password" name="passwd"/>
58
Form Elements
Radio button: provides users a means to select
one from previously listed items
Company size (people): <br/>
10~19 <input type="radio" name="csize" value="10_19" checked/> <br/>
20~49 <input type="radio" name="csize" value="20_49"/> <br/>
50~99 <input type="radio" name="csize" value="50_99"/> <br/>
above <input type="radio" name="csize" value="above"/>
59
Form Elements
Checkboxes: provides users a means to select zore or
more items from previously listed items
Languages:<br/>
English <input type="checkbox" name="languages" value="English"/><br/>
French <input type="checkbox" name="languages" value="French"/><br/>
Japanese <input type="checkbox" name="languages" value="Japanese"/><br/>
Chinese <input type="checkbox" name="languages" value="Chinese"/><br/>
60
Forms Elements
Submit and Reset button
<form name="signin">
Username: <input type="text" name="email"/> <br/>
Password: <input type="password" name="passwd"/> <br/>
<input type="reset" name="reset" value="Reset"/>
<input type="submit" name="submit" value="Submit"/>
</form>
61
62
Form Elements
A dropdown list allows users to select one from a list of items
City:
<br/>
<select size="1">
<option value="HCM">Ho Chi Minh</option>
<option value="HN">Hanoi</option>
<option value="DN">Danang</option>
</select>
63
From Processing
<script type="text/javascript">
function formCheck(){
var form=document.signup;
if(!(form.passwd.value==form.repasswd.value)){
alert("Password mismatched!");
}
}
</script>
64
65
66