Chapter-3 Javascript
Chapter-3 Javascript
JAVASCRIPT
1
WHAT CAN YOU DO WITH
JAVASCRIPT?
Validate form fields
Dynamically alter the appearance of a page element
Hide and show elements
Move elements about the page
Capture user events and adjust the page accordingly
Interface with a server-side application without leaving the
page
2
"HELLO WORLD!"
Javascript is easy
Script tags are added to the head/body element in the document
<script type="text/javascript">
...some JavaScript
</script>
3
JAVASCRIPT CODE LOCATION
Place the JavaScript in the body
when the JavaScript dynamically creates web
page content as the page is being loaded.
Place the JavaScript in the head tag
When the JavaScript defined in functions and
used for page events, as this is loaded before
the body.
4
CONTINUE….
1. How to add JavaScript to an HTML page
1. Using the <script> tag in the <head>part of the html page. Example
<head>
<script>
</script>
</head>
2. Using the <script> tag and including an external JavaScript file.
Example
<head>
<script src="j7.js"></script>
</head>
3. Anywhere in the HTML document. Example
<body>
<script>
</script>
</body>
EG
6
JAVASCRIPT FILES
To include a JavaScript library or script file in your web
page, use this syntax:
<script type="text/javascript"
src="somejavascript.js"></script>
The script element contains no content, but the closing
tag is still required
A script file is treated as if the code is actually included
in the page; the behavior is the same between script files
and embedded JavaScript blocks.
7
JavaScriptData Types
and Variables
8
DATA TYPES
JavaScript is forgiving
If you start out with a string => then want to
use it as a number, that's perfectly fine with
the language.
Context is everything when it comes to JavaScript data
typing/ variable.
Because JavaScript is case-sensitive, variable names are
case-sensitive.
There are just three simple data types:
string,
numeric, and
Boolean.
9
STRING DATA TYPE
A string literal is a sequence of characters delimited by
single or double quotes:
"This is a string"
'But this is also a string'
var string_value = "This is the first
line\nThis is the
second line";
to include a quote within the quoted string,
Use a single and double quotes can be used
interchangeably
var string_value = "This is a
'string' with a quote."
or:
var string_value = 'This is a
"string" with a quote.' 10
NUMBER DATA TYPE
Numbers in JavaScript are floating-point numbers,
All of the following are valid floating-point numbers:
0.3555 , 144.006 , -2.3 , 19.5e-2 (which is
equivalent to 19.5-2)
octal and hexadecimal notation can be used
A hexadecimal number begins with a zero,
followed by an x:
0xCCFF
Octal values begin with zeros, and there is no
leading x:
0526
11
NULL AND UNDEFINED
Not declared
alert(sValue); // results in JavaScript error
because sValue is not declared first
A null variable is one that has been defined, but hasn't
been assigned a value.
var sValue;
alert(sValue); // no error, and a window
with the word 'undefined' is opened
If the variable has been declared but not initialized, it is
considered undefined
Constants
const CURRENT_MONTH = 3.5;
12
CHANGING DATA TYPES
parseInt and
Function toString toBoolean
parseFloat
1 if true ;
Boolean “true” / “false” Value of value
otherwise 0
false if 0 or NaN;
Number String number Straight value
otherwise, TRue
false if string
String No conversion is empty; Number portion
otherwise, true
A string Numeric
representation representation of
Object of the default TRue the default
representation representation of
of the object the object 13
Operators and Statements
14
SIMPLE STATEMENTS
Assignment
NValue = 35.00;
nValue = nValue + 35.00;
nValue = someFunction( );//function
call
var firstName = lastName =
middleName = ""; //more than one
assignment is possible
Arithmetic Statements
Concatenation ( “+” used with string)
var newString = "This is an old " +
oldString;
Multiplication ( “*” used with numbers)
var newValue = 3.5 * 2.0; // result is 7
var newValue = 3.5 * "2.0"; // result is
still 7 15
var newValue = "3.5" * "2.0"; // still 7
CONT'D . . . SIMPLE STATEMENTS
Since + is used as a concatenation with string.
var newValue = 3.5 + "2.0"; // result is
3.52.0
Better way to use is by explicitly converting the value
var aVar = 3.5 + parseFloat("2.3 the sum
is ");
document.write(aVar); // result is 5.8
The Unary Operators
++ Increments a value
-- Decrements a value
- Represents a negative value
Ternary Operator
condition ? value if true; value if
false;
Logical Operators
AND (&&) , OR (||) , NOT(!)
16
CONDITIONAL STATEMENTS AND
PROGRAM FLOW
if
if...else
Switch
17
THE LOOPS
While
do...while
For ( two types )
First type
For (initial value; condition;
update) {
… }
second type of the for loop is a for...in loop
which accesses each element of the array as a
separate item. The syntax for this handy
statement is:
for (variable in object) {
...
}
18
EXAMPLES
<html>
<body>
<script type="text/javascript">
var i=0;
while (i<=5)
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
</script>
</body>
</html>
CONTINUE..
<html>
<body>
<script type="text/javascript">
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
while (i<=5);
</script>
</body> </html>
EG FOR IN LOOP
<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>
</body>
</html
21
JAVASCRIPT POPUP BOXES
three kinds of popup boxes: Alert box, Confirm box, and Prompt
box.
Alert Box
Used if you want to make sure information
comes through to the user.
alert("sometext");
Confirm Box
used if you want the user to verify or accept
something.
confirm("sometext");
Prompt Box
used if you want the user to input a value
before entering a page.
prompt("sometext","defaultvalue");
22
EG ALERT BOX
<html>
<head>
<script type="text/javascript">
function disp_alert() {
alert("I am an alert box!!");
}
</script>
</head>
<body>
<input type="button"
onclick="disp_alert()"
value="Display alert box" />
</body>
</html>
23
EG CONFIRM 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> 24
EG PROMPT BOX
<html>
<head>
<script type="text/javascript">
function disp_prompt()
{
var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="") {
document.write("Hello " + name + "! How are you today?");
}
}
</script>
</head>
<body>
</body>
</html>
25
The JavaScript Objects
26
OBJECTS FROM FOUR DIFFERENT
DOMAINS
Those built into JavaScript
are those that are built into JavaScript as
language-specific components
Eg: data types Numbers, Strings, Boolaean
special-purpose objects, such as Math, Date,
and RegExp.
built-in aggregator object, Array
27
AN OBJECT
An object has properties and methods .
Properties
values associated with an object.
var txt="Hello World!";
document.write(txt.length); // result 12
methods
actions that can be performed on objects
var str="Hello world!";
document.write(str.toUpperCase()); //result
HELLO WORLD!
28
THE NUMBER OBJECT
The object also has four constant numeric properties,
directly accessible from the Number object.
MAX_VALUE - Returns the largest possible value in JavaScript
29
THE STRING OBJECT
is used to manipulate a stored piece of text.
Created by:
var sObject = new String("Sample string"); // OR
var sObject = "Sample string";
Eg Methods: the concat method
var sObj = new String( );
var sTxt = sObj.concat("This is a ", "new
string");
Result:
This is a new string
The indexOf() method
Used to return the position of the first occurrence of a specified string
value in a string. Result:
0
var str="Hello world!"; -1 none
document.write(str.indexOf("Hello") + "<br 6
/>");
document.write(str.indexOf("World") + "<br
/>"); 30
document.write(str.indexOf("world"));
STRING OBJECT METHODS
Eg match(): similar to indexOf() and lastIndexOf(), but it returns
the specified value, instead of the position of the string.
var str="Hello world!";
document.write(str.match("world") + "<br Result:
/>"); world
document.write(str.match("World") + "<br null
/>"); null
document.write(str.match("worlld") + world!
"<br />");
document.write(str.match("world!"));
search() Searches a string for a specified value
slice() Extracts a part of a string and returns the extracted part in a new
string
small() Displays a string in a small font
split() Splits a string into an array of strings
strike() Displays a string with a strikethrough
sub() Displays a string as subscript
33
CONT'D ... STRING OBJECT METHODS
substr() Extracts a specified number of characters in a
string, from a start index
substring() Extracts the characters in a string
between two specified indices
sup() Displays a string as superscript
toLowerCase() Displays a string in lowercase letters
toUpperCase() Displays a string in uppercase letters
toSource() Represents the source code of an object
valueOf() Returns the primitive value of a String object
34
EG STYLING TEXT
var txt="Hello World!";
36
CONT'D . . . STRING METHODS
Split
has two parameters
stringObject.split(separator, howmany)
The first is the character that marks each
break;
the second is the number of splits to perform.
var str="How are you doing today?";
Result:
How,are,you,doing,today?
H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,? 37
How,are,you
EG
var inputString =
'firstName=Shelley,lastName=Powers,state=Missouri,
statement="This is a test of split"';
var arrayTokens = inputString.split(',',4);
for (var i in arrayTokens) {
document.writeln(arrayTokens[i] + "<br />");
var newTokens = arrayTokens[i].split('=');
document.writeln(newTokens[1] + "<br />");
}
Result :
firstName=Shelley
Shelley
lastName=Powers
Powers
state=Missouri
Missouri
38
statement="This is a test of split"
"This is a test of split"
DATE OBJECTS
The Date
create a date and then access any aspect of it
year, day, second, and so on.
var dtNow = new Date( );
document.writeln(dtNow);
Output:
Thu Apr 2 2009 12:08:38 GMT+0300
to create a specific date (use proper format!)
var nowDt = new Date("March 12, 1984
12:20:25");
var newDt = new Date(1977,12,23);
var newDt = new Date(1977,11,24,19,30,30,30);
in order of year, month (as 0 to 11), day, hour, minutes,
seconds, and milliseconds.
39
DATE OBJECTS
The Date object methods get and set specific components of the
date
getFullYear
getHours
getMilliseconds
getMinutes
getMonth
getSeconds
GetYear
eg.
var dtNow = new Date( );
alert(dtNow.getDay( )); // if run on friday result:5
40
COMPARE TWO DATES
if (myDate>today) {
document.write("Today is before 14th January 2010");
}
Else {
document.write("Today is after 14th January 2010");
} 41
AN ARRAY TO WRITE A WEEKDAY
<html>
<body>
<script type="text/javascript">
var d=new Date();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
Result: Today it is Friday
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
document.write("Today it is " + weekday[d.getDay()]);
</script>
</body>
42
</html>
MATH OBJECTS
allows you to perform mathematical tasks
Math's properties and methods are static (can not create new
instance)
var newValue = Math.SQRT1;
Math's properties
To access use Math.property
E - Value of e, the base of the natural logarithms
LN10 - The natural logarithm of 10
LN2 - The natural logarithm of 2
LOG2E - The approximate reciprocal of LN2the base-
2 logarithm of e
LOG10E - The approximate reciprocal of LN10the
base-10 logarithm of e
PI - The value of PI
SQRT1_2 - The square root of 1/2
43
SQRT2 - The square root of 2
CONT'D . . . MATH OBJECTS
The Math Methods
eg.
Math.abs( ) - Computes an absolute value. var nVal = -3.45;
Math.ceil( ) - Rounds a number up. var pVal = Math.abs(nVal);
Math.cos( )- Computes a cosine.
Math.exp( ) - Computes a power of e.
document.write(Math.round(4.7));
Output: 5
Math.floor( ) - Rounds a number down.
Math.log( ) - Computes a natural logarithm.
Math.max( ) - Returns the larger of two numbers.
Math.min( ) - Returns the smaller of two numbers.
Math.pow( ) - Computes x^y
Math.random( ) - Computes a random number.
Math.round( ) - Rounds to the nearest integer.
Math.sin( ) - Computes a sine.
Math.sqrt( ) - Computes a square root.
Math.tan( ) - Computes a tangent
44
EG.
45
JAVASCRIPT ARRAYS
Constructing Arrays
with a constructor
var newArray = new Array('one','two');
As a literal value
var newArray = ['one','two'];
Multi-dimensional array
var threedPoints = new Array( );
document.writeln(threedPoints[0][1]);
46
ARRAY PROPERTIES
length – the length of an array
var testArray = new Array( );
testArray[99] = 'some value'; //set size 100
alert(testArray.length);
Output: 100
Splice - returns selected elements from an existing array.
47
ARRAY
Concat - concatenates one array onto the end of the other:
var arr = new Array(3);
arr[0] = "Jani";
arr[1] = "Tove";
arr[2] = "Hege"; Output:
Jani,Tove,Hege,John,Andy,Wend
y
var arr2 = new Array(3);
arr2[0] = "John";
arr2[1] = "Andy";
arr2[2] = "Wendy";
document.write(arr.concat(arr2));
Neither concat nor slice alter the original array. Instead, they 48
return an array containing the results of the operation.
CONT'D . . . ARRAY PROPERTIES
Use of for . . . in
var programLanguages = new Array ('C++','Pascal',
'FORTRAN','BASIC','C#','Java','Perl','JavaScript');
49
LITERAL ARRAY - SORT()
var arr = new Array(6);
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";
arr[5] = "Tove";
Output:
Jani,Hege,Stale,Kai Jim,Borge,Tove
Borge,Hege,Jani,Kai Jim,Stale,Tove
50
ASSOCIATIVE ARRAYS
doesn't have a numeric index
Object is normally used
var assocArray = new Object( );
assocArray["one"] = "Show one";
assocArray["two"] = "Show two";
document.writeln(assocArray["two"]<br />);
document.writeln(assocArray.one);//accessed
as object
Output:
Show two
Show one
51
JavaScript
Applications
52
BROWSER DETECTION BY NAVIGATOR
OBJECT
JavaScript includes an object called the Navigator object
which contains information about the visitor's browser
name, browser version, and more.
appName Returns the name of the browser
appVersion Returns the platform and version of the browser
browserLanguage Returns the current browser language
cookieEnabled Returns a Boolean value that specifies
whether cookies are enabled in the browser
platform Returns the operating system platform
systemLanguage Returns the default language used by the OS
53
BROWSER DETECTION
<html>
<body>
<script type="text/javascript">
var browser=navigator.appName;
var b_version=navigator.appVersion;
var version=parseFloat(b_version);
55
EG FORM VALIDATION
<body>
<html> <form action="submitpage.htm"
<head> onsubmit="return validate_form(th
<script type="text/javascript">
method="post">
Email: <input type="text"
function validate_required(field,alerttxt)
name="email" size="30">
{
<input type="submit"
with (field) { value="Submit">
if (value==null||value=="") </form>
{alert(alerttxt); return false;} </body>
else {return true}
} </html>
}
function validate_form(thisform) {
with (thisform) {
if (validate_required(email,"Email must be filled out!")==false)
{email.focus();return false;}
}
}
</script>
56
</head>
EMAIL VALIDATION
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
59