You are on page 1of 43

Introduction to JavaScript

Version 1.0
What is Java Script?
•JavaScript is NOT Java.
•Developed by Netscape.
•Purpose: Execute on the client-side
(browser)
•Widely used within HTML pages, for client-
side validation, etc.
•It is similar to Java, but loosely typed data.
•JavaScript is interpreted programming
language.
•Errors are identified by browsers.

TCS Internal September 3, 2009


JavaScript Within HTML page
<html>
<head>
<title>JavaScript Page</title> Script
Declaration
<script LANGUAGE=“JavaScript”> Tag

<!-- actual JavaScript follows below

alert (“Welcome to the Test Site!”);

// ending the script --> JavaScript


Function
</script>
</head>
<body> Content of the Page </body>
</html> TCS Internal September 3, 2009
Data Types
•Numerical data
– Integers
– Floating-point numbers
•Text data
– String
•Boolean data
– True/false

TCS Internal September 3, 2009


Declaring variables
•Weekly typed language.
•Example:
– var myname=“david”;
– var myint = 1234;

TCS Internal September 3, 2009


Operations
•Normal numerical calculations like any other
programming language is possible.
•Example:
var a = 10;
var b = 20;
var c = a + b;
•String operations are similar to Java.
•Example:
String s = “one”;
String t = “two”;
String u = s + t; ( will result in
TCS Internal September 3, 2009
“onetwo”)
Native Objects
•Array
– Arrays are treated as objects like in Java
– Multidimensional arrays are treated as
array of arrays.
– Arrays can have holes.
•Means some elements in the array may
be empty.
•Examples:
var firstArray = new Array(); // creating a
new array
var secondArray = new Array(“Bob”, Arrays can hold
different type of data
“Clinton”, 123); TCS Internal September 3, 2009
Native Objects
•String
– Strings are similar to Java String.
– All String related methods are available.
– Examples:
•myString.length;
•myString.subString(0, 3);
•myString.charAt(3);

TCS Internal September 3, 2009


Native Objects
•Math
– Provides useful mathematical functions.
– Examples:
•round()
•floor()
•abs()

TCS Internal September 3, 2009


Native Objects
•Date
– Handling date/colander related functions
– Examples:
•getDate()
•getDay()
•getMonth()

TCS Internal September 3, 2009


Browser Related Objects
•Window object
– Location object
– History object
– Document object
•Forms object
•Images object
•Links object
– Navigator object
– Screen object

TCS Internal September 3, 2009


JavaScript Examples

September 3, 2009RMIT - JavaScript Examples


Format
The script must be between script tags:
•<SCRIPT LANGUAGE = "JavaScript">
•<!-- HIDE FROM OTHER BROWSERS
•….. code goes here …..
•//STOP HIDING FROM OTHER
BROWSERS-->
•</SCRIPT>
Note the comments are used to prevent
problems in old browsers

TCS Internal September 3, 2009 13


Input Output
<script language=“JavaScript”>
var celsius, fahrenheit
celsius = prompt ("Enter Temperature in
Celsius", "20")
celsius = parseFloat (celsius)
fahrenheit= celsius * 9.0 / 5.0 + 32.0
document.write ("Temperature in Fahrenheit
is: ")
document.writeln (fahrenheit)
</script>

TCS Internal September 3, 2009 14


Selection
•The if statement is from Java and C++:
if (hours <= 40)
{
wage = hours * rate
}
else
{
wage = (hours - 40) * rate * 1.5 + 40 *
rate
}
TCS Internal September 3, 2009 15
While
•The while statement is from Java and C++:
number = 1
while (number <= 4)
{
document.writeln (number)
number ++
}
•Note the number ++

TCS Internal September 3, 2009 16


For
•The for statement is from Java and C++:
var number
for (number=1; number <= 4; number++)
{
document.writeln (number)
}
•Note again the number ++

TCS Internal September 3, 2009 17


Function
•It is common to put code in the header
inside of a function
function calculate ( )
{ var celsius, fahrenheit
celsius = prompt ("Enter Temperature in
Celsius", "20")
celsius = parseFloat (celsius)
fahrenheit= celsius * 9.0 / 5.0 + 32.0
document.write ("Temperature in Fahrenheit
is: ")
document.writeln (fahrenheit)
}
TCS Internal September 3, 2009 18
Function1
•It is best to use arguments and a return
function calculate (celsius)
{
return (celsius * 9.0 / 5.0 + 32.0)
}
•To call function use:
fahrenheit = calculate (celsius)

TCS Internal September 3, 2009 19


Math
•Math functions are like in Java
•They are messages sent to the class Math
numberOut = Math.sqrt (numberIn)

TCS Internal September 3, 2009 20


Repeat
•The iteration with test after is simulated
var flag = true
while (flag)
{
calculate()
flag = confirm("Do you wish to do
another?")
}
•Note confirm dialog box

TCS Internal September 3, 2009 21


Date
function getFullYear()
{
var year = this.getYear()
year += 1900
return year
}

TCS Internal September 3, 2009 22


Date

function getActualMonth()
{
var month = this.getMonth()
month ++
return month
}

TCS Internal September 3, 2009 23


Date
•Here are some more useful ones :
function getCalendarDay ( )
{ var day = this.getDay ( )
var days = new Array (7)
days[0] = "Sunday"
days[1] = "Monday"
days[2] = "Tuesday"
days[3] = "Wednesday"
days[4] = "Thursday"
days[5] = "Friday"
days[6] = "Saturday"
return days [day]
}
TCS Internal September 3, 2009 24
Alert
•JavaScript also has a message box:

var string
string = “message”
alert (string)

TCS Internal September 3, 2009 25


Browser
•Need to tell you about the properties of the
object document
•document.writeln("Browser name: " +
navigator.appName)
•document.writeln("Browser version: " +
navigator.appVersion)
•document.writeln("Browser platform: " +
navigator.platform)
•document.writeln("Browser plugins: " +
navigator.plugins)

TCS Internal September 3, 2009 26


Form1
•This form uses a function invoked by a
button called name1
function callAlert (form)
{ alert ("Your name is: "+
form.name1.value)
}
<FORM>
<INPUT TYPE="text" NAME="name1" SIZE
= 10>
<INPUT TYPE="button" NAME="show"
VALUE="Show" onClick="callAlert
(this.form)">TCS Internal September 3, 2009 27
Form2
•This form uses a function invoked by a
button to populate the form
function convertTemp (form)
{ var fahrenheit, celsius
celsius = parseFloat (form.celsius.value)
fahrenheit = celsius * 9.0 / 5.0 + 32.0
form.fahrenheit.value = fahrenheit
}
<INPUT TYPE="button"
NAME="compute" VALUE="Compute"
onClick="convertTemp (this.form)">
TCS Internal September 3, 2009 28
Form3
•This form shows the mail form that will be used in the next
examples
•There is no JavaScript
<FORM METHOD="post”
ACTION="mailto:stumpf@bf.rmit.edu.au">
<PRE>
Name: <INPUT TYPE="text" size=25
name="name"><BR>
Age: <INPUT TYPE="text" size=25
name="age"><BR>
Gender: <INPUT TYPE="text" size=25
name="gender"><BR>
Email: <INPUT TYPE="text" size=25
name="email"><BR>
<INPUT TYPE="submit" VALUE="Register">
TCS Internal September 3, 2009 29
Form4
•This form shows the addition of a list box to the
mail form
•There is still no JavaScript
Interest:<SELECT NAME="whatInterest" SIZE=4>
<OPTION VALUE="Web">World Wide Web
</OPTION>
<OPTION VALUE="Java">Java Programming
</OPTION>
<OPTION VALUE="C++">C++
Programming </OPTION>
<OPTION VALUE="Javascript">Javascript
</OPTION>
<OPTION VALUE="UML">UML
TCS Internal September 3, 2009 30
Form5
•This form uses a function invoked by ONSUBMIT =
“return checkFields (form1)”
function checkFields(form)
{ var validFlag = true
for (var i = 0; i < 5; i++)
{ if (form.elements[i].value == null ||
form.elements[i].value == "")
{ validFlag = false
alert ("The " + form.elements[i].name
+
" field is blank. Please enter a
value.")
break
}
} TCS Internal September 3, 2009 31
Form6
•This form adds more advanced checking of
form
if (parseInt (form.elements[1].value) < 21)
{ alert ("At :" + form.age.value + " you
are too young")
validFlag = false
}
if ( ! ( form.gender[0].checked)&& !
( form.gender[1].checked))
{ alert ("Please check gender")
validFlag = false
}
TCS Internal September 3, 2009 32
Hidden
•This form identifies the browser and tells the
both the client and server
if (( browser == "Netscape") ||
( browser == "Microsoft Internet
Explorer"))
{ alert ("You are using " + browser +
version)
}
else
{ alert ("What browser are you using?")
}
TCS Internal September 3, 2009 33
Frame
•Here is the frame set:
<HTML>
<HEAD>
<TITLE>Demonstration of frames using Java
Script</TITLE>
</HEAD>
<FRAMESET COLS="25%,*">
<FRAME SRC="frameleft.htm"
NAME="frameLeft">
<FRAME SRC="frameright1.htm"
NAME="frameRight">
</FRAMESET>
TCS Internal September 3, 2009 34
Frame
•Here are the functions in the left frame
invoked by radio buttons and on load:
function setButton(form)
{ form.button1[0].checked=true
}
function opendoc1()
{
parent.frameRight.location.href="frameright
1.htm"
}
function opendoc2()
{
TCS Internal September 3, 2009 35
New Window
•Upon clicking the Okay button, the page
links to another site:
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS
alert("After this you will open a new
window")
window.location.href =
"http://www.cisdept.csupomona.edu/"
//STOP HIDING FROM OTHER BROWSERS--
>
</SCRIPT> TCS Internal September 3, 2009 36
Cookie
•A cookie is not something to eat
•It is a text file on your c:\ drive written by a
function in JavaScript; for example:
www.csupomona.edu
FALSE /C|/stumpf/javascript FALSE
938049354 Title Mr

FALSE /C|/stumpf/javascript FALSE


938129386 UserName Robert Stumpf

TCS Internal September 3, 2009 37


Cookie
•The critical parts are the cookie name and
cookie value, for example:

Title Mr

UserName Robert Stumpf

TCS Internal September 3, 2009 38


Cookie
•The critical methods are:
• getCookie(name)
• setCookie (name, value,expires,
path,domain,secure)

TCS Internal September 3, 2009 39


Cookie
•Checking a cookie:
function checkCookie ( )
{ var title=null, userName=null
var name, value, expires
var path=null ,domain=null,secure=null
expires = new Date ( );
expires.setTime (expires.getTime ( ) + 24*60*60*365*1000) //
Plus one year
name = "UserName"
userName = getCookie(name)
if (userName == null)
userName = prompt("Please Enter Your Name:","")
value = userName
setCookie (name,value,expires,path,domain,secure)
return (title + " " + userName)
TCS Internal
} September 3, 2009 40
Password
•Checking a password:
function checkpw (form)
{ var passwordKeyed =
form.passwordKeyed.value
var passwordCookie = getCookie
("PassWord")
if (passwordKeyed == passwordCookie)
parent.frameLeft.opendoc3 ( )
else
alert ("Password did not match, try
again.")
}
TCS Internal September 3, 2009 41
Password
•Verifying a new password:
function checkpw (form)
{ var password1 = form.password1.value
var password2 = form.password2.value
var name, value, expires, path=null ,domain=null,secure=null
expires = new Date ( );
expires.setTime (expires.getTime ( ) + 24*60*60*365*1000)
if (password1 == password2)
{ name = "PassWord"
value = password1
setCookie(name,value,expires,path,domain,secure)
parent.frameLeft.opendoc3 ( )
}
else
alert("Passwords did not match, try again.")
}
TCS Internal September 3, 2009 42
Reference:
•Beginning JavaScript, 2nd Edition, Paul
Wilton, Wrox Publishers, 2004.

TCS Internal September 3, 2009

You might also like