BCA212 - Unit 4
BCA212 - Unit 4
UNIT 4:
Java Script: Introduction to Documents, forms, Statements, functions, objects in Javascript, Arrays,
Forms, Buttons, Checkboxes, Text fields and Text areas.
JavaScript
JavaScript was designed to add interactivity to HTML pages
JavaScript is a scripting language
A scripting language is a lightweight programming language
JavaScript is usually embedded directly into HTML pages
JavaScript is an interpreted language (means that scripts execute without preliminary
compilation)
Everyone can use JavaScript without purchasing a license
The example below shows how to use JavaScript to write text on a web page:
<html>
<body>
<script type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html>
The example below shows how to add HTML tags to the JavaScript:
<html>
<body>
<script type="text/javascript">
document.write("<h1>Hello World!</h1>");
</script>
</body>
</html>
To insert a JavaScript into an HTML page, we use the <script> tag. Inside the <script> tag we use the type
attribute to define the scripting language.
So, the <script type="text/javascript"> and </script> tells where the JavaScript starts and ends:
<html>
<body>
<script type="text/javascript">
...
</script>
</body>
</html>
The document.write command is a standard JavaScript command for writing output to a page. By entering
the document.write command between the <script> and </script> tags, the browser will recognize it as a
JavaScript command and execute the code line. In this case the browser will write Hello World! to the
page:
<html>
<body>
<script type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html>
Note: If we had not entered the <script> tag, the browser would have treated the document.write("Hello
World!") command as pure text, and just write the entire line on the page.
Just add an HTML comment tag <!-- before the first JavaScript statement, and a --> (end of comment)
after the last JavaScript statement, like this:
<html>
<body>
<script type="text/javascript">
<!--
document.write("Hello World!");
//-->
</script>
</body>
</html>
The two forward slashes at the end of comment line (//) is the JavaScript comment symbol. This prevents
JavaScript from executing the --> tag.
JavaScript can be put in the body and in the head sections of an HTML page.
Scripts in <head>
Scripts to be executed when they are called, or when an event is triggered, are placed in functions. Put
your functions in the head section, this way they are all in one place, and they do not interfere with page
content.
Example
<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>
<body onload="message()">
</body>
</html>
Scripts in <body>
If you don't want your script to be placed inside a function, or if your script should write page content, it
should be placed in the body section.
Example
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.write("This message is written by JavaScript");
</script>
</body>
</html>
Example
<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>
<body onload="message()">
<script type="text/javascript">
document.write("This message is written by JavaScript");
</script>
</body>
</html>
Note: Remember to place the script exactly where you normally would write the script! JavaScript is a
sequence of statements to be executed by the browser.
JavaScript Statements
A JavaScript statement is a command to a browser. The purpose of the command is to tell the browser
what to do.
This JavaScript statement tells the browser to write "Hello Dolly" to the web page: document.write("Hello
Dolly");
It is normal to add a semicolon at the end of each executable statement. Most people think this is a good
programming practice, and most often you will see this in JavaScript examples on the web.
The semicolon is optional (according to the JavaScript standard), and the browser is supposed to interpret
the end of the line as the end of the statement. Because of this you will often see examples without the
semicolon at the end.
Note: Using semicolons makes it possible to write multiple statements on one line.
JavaScript Code
JavaScript code (or just JavaScript) is a sequence of JavaScript statements. Each statement is executed by
the browser in the sequence they are written. Following example will write a heading and two paragraphs
to a web page:
Example
<script type="text/javascript">
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
</script>
JavaScript Blocks
JavaScript statements can be grouped together 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. Following example will write a heading and two paragraphs to a web page:
Example
<script type="text/javascript">
{
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph tested at pmc.</p>");
}
</script>
The example above is not very useful. It just demonstrates the use of a block. Normally a block is used to
group statements together in a function or in a condition (where a group of statements should be
executed if a condition is met).
JavaScript Variables
As with algebra, JavaScript variables are used to hold values or expressions. A variable can have a short
name, like x, or a more descriptive name, like carname.
After the declaration shown above, the variables are empty (they have no values yet). However, you can
also assign values to the variables when you declare them:
var x=5;
var carname="Volvo";
After the execution of the statements above, the variable x will hold the value 5, and carname will hold
the value Volvo.
Note: When you assign a text value to a variable, use quotes around the value.
These statements:
x=5;
carname="Volvo";
After the execution of the statements above, the variable x will still have the value of 5. The value of x is
not reset (or cleared) when you redeclare it.
JavaScript Arithmetic
As with algebra, you can do arithmetic operations with JavaScript variables:
y=x-5;
z=y+5;
Comparison Operators
Comparison operators are used in logical statements to determine equality or difference between
variables or values.
Given that x=5, the table below explains the comparison operators:
Logical Operators
Logical operators are used to determine the logic between variables or values. Given that x=6 and y=3,
the table below explains the logical operators:
Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on
some condition.
Syntax
variablename=(condition)?value1:value2
Example
greeting=(visitor=="PRES")?"Dear President ":"Dear ";
If the variable visitor has the value of "PRES", then the variable greeting will be assigned the value "Dear
President " else it will be assigned "Dear".
Flow Control
• Conditional statements are used to perform different actions based on different conditions.
• In JavaScript we have the following conditional statements:
• if statement - use this statement to execute some code only if a specified condition is true
• if...else statement - use this statement to execute some code if the condition is true
and another code if the condition is false
• if...else if....else statement - use this statement to select one of many blocks of code to be
executed
• switch statement - use this statement to select one of many blocks of code to be executed
Looping Structures
• Often when you write code, you want the same block of code to run over and over again in a row.
Instead of adding several almost equal lines in a script we can use loops to perform a task like this.
• In JavaScript, there are two different kind of loops:
• for - loops through a block of code a specified number of times
• while - loops through a block of code while a specified condition is true
Syntax
for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}
Example
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
Syntax
while (var<=endvalue)
{
code to be executed
}
Example
<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>
Syntax
do
{
code to be executed
}
while (var<=endvalue);
Example
The example below uses a do...while loop. The do...while loop will always be executed at least once, even
if the condition is false, because the statements are executed before the condition is tested:
<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>
The Break Statement
The break statement will break the loop and continue executing the code that follows after the loop (if
any).
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
Syntax
for (variable in object)
{
code to be executed
}
Note: The code in the body of the for...in loop is executed once for each element/property.
Example: Use the for...in statement to loop through an array:
<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>
Functions
• A function is simply a block of code with a name, which allows the block of code to be called by other
components in the scripts to perform certain tasks.
• Functions can also accept parameters that they use complete their task.
• JavaScript actually comes with a number of built-in functions to accomplish a variety of tasks.
function name_of_function(argument1,argument2,…arguments)
{
…………………………………………
//Block of Code
…………………………………………
}
Calling functions
• There are two common ways to call a function: From an event handler and from another function.
• Calling a function is simple. You have to specify its name followed by the pair of parenthesis.
<SCRIPT TYPE="TEXT/JAVASCRIPT">
name_of_function(argument1,argument2,…arguments)
</SCRIPT>
Example
<html>
<head> <title>PMC</title>
<Script Language="JavaScript">
function welcomeMessage()
{
document.write("Welcome to Patan Campus!");
}
</Script>
</head>
<body>
<h1>Patan Multiple Campus CSIT</h1>
<h3>Testing the function in PMC</h3>
<Script Language="JavaScript">
welcomeMessage();
</Script>
</body>
</html>
Popup Boxes
Alert Box:
An alert box is often used if you want to make sure information comes through to the user. When an alert
box pops up, the user will have to click "OK" to proceed.
Syntax
alert("sometext");
Example
<html>
<head>
<script type="text/javascript">
function show_alert()
{
alert("I am an alert box!");
}
</script>
</head>
<body>
<input type="button" onclick="show_alert()" value="Show alert box" />
</body>
</html>
Confirmation Box:
A confirm box is often used if you want the user to verify or accept something. When a confirm box pops
up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns
true. If the user clicks "Cancel", the box returns false.
Syntax
confirm("sometext");
Example
<html>
<head>
<script type="text/javascript">
function show_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="show_confirm()" value="Show confirm box" />
</body>
</html>
Prompt Box:
A prompt box is often used if you want the user to input a value before entering a page. When a prompt
box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.
Syntax
prompt("sometext","defaultvalue");
Example
<html>
<head>
<script type="text/javascript">
var name=prompt("Please enter your name",“Rajendra");
</script>
</head>
<body>
<script type="text/javascript">
document.write("Hello "+name + "You have worked will with variables");
</script>
</body>
</html>
JavaScript objects
JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your
own objects and make your own variable types. An object is just a special kind of data. An object has
properties and methods.
There are three ways of adding values to an array (you can add as many values as you need to define as
many variables you require).
1.) Conventional array: The classic conventional array looks like the following:
2.) Condensed array: The second way of defining an array is called a condensed array, array elements
definitions into one step:
This is convinient if you know all the array element values in advance.
3.) Literal array: Finally, we arrive at literal arrays. Introduced in JavaScript1.2 and support by all modern
browsers (IE/NS4+), literal arrays sacrifice intuitiveness somewhat in exchange for tremendous
robustness. The syntax looks like:
var myCars=["Saab","Volvo","BMW"];
As you can see, enclose all the array elements within an outter square bracket ([ ]), each separated by a
comma (,). To create array elements with an initial undefined value just enter a comma (,) as shown in the
second example above.
Literal arrays really shine when it comes to defining multi-dimensional arrays. It is as easyas adding
containing brackets ([ ]) within the outermost bracket. For example:
Here the first array element is actually a two dimensional array in itself containing various cities names.
Let's illustrate with an example: A person is an object. Properties are the values associated with the object.
The persons' properties include name, height, weight, age, skin tone, eye color, etc. All persons have these
properties, but the values of those properties will differ from person to person. Objects also have
methods. Methods are the actions that can be performed on objects. The persons' methods could be
eat(), sleep(), work(), play(), etc.
The syntax for accessing a property of an object is:
objName.propName
Note: Parameters required for the method can be passed between the parentheses. There are different
ways to create a new object:
personObj=new Object();
personObj.firstname="Jyoti";
personObj.lastname="Joshi";
personObj.age=25;
personObj.eyecolor="black";
Adding a method to the personObj is also simple. The following code adds a method called eat() to the
personObj:
personObj.eat=eat;
function eat( )
{
// code for the function
}
When an HTML page is rendered in a browser, the browser assembles all the elements (objects) that are
contained in the HTML page, downloaded from web-server in its memory. Once done the browser then
renders these objects in the browser window as text, forms, input boxes, etc. Once the HTML page is
rendered in web-browser window, the browser can no longer recognize individual HTML elements
(Objects).
Since the JavaScript enabled browser uses the Document Object Model (DOM), after the page has been
rendered, JavaScript enabled browsers are capable of recognizing individual objects in an HTML page.
The HTML objects, which belong to the DOM, have a descending relationship with each other.
The topmost object in the DOM is the Navigator (i.e. Browser) itself. The next level in the DOM is the
browser's Window, and under that are the Documents displayed in Browser's Window.
Fig: HTML DOM Tree Example
formObject.method=value
Value Description
Get Appends the form-data to the URL: URL?name=value&name=value (this is default)
post Sends the form-data as an HTTP post transaction
Form Validation:
Form validation is the process of checking that a form has been filled in correctly before it is processed.
For example, if your form has a box for the user to type their email address, you might want your form
handler to check that they've filled in their address before you deal with the rest of the form.
There are two main methods for validating forms: server-side (using CGI scripts, ASP, etc), and client-side
(usually done using JavaScript). Server-side validation is more secure but often more tricky to code and it
also increases load of server computer, whereas clientside (JavaScript) validation is easier to do and
quicker too (the browser doesn't have to connect to the server to validate the form, so the user finds out
instantly if they've missed out that required field!) and it also decreases the load of server computer and
hence server computer can focus on business logic processing.
<script type='text/javascript'>
function notEmpty()
{
var v= document.getElementById('elem').value;
if(v.length == 0)
{
alert("Field should not be empty:");
document.getElementById('elem').value=” ”;
document.getElementById('elem').focus();
}
}
</script>
<form>
Required Field: <input type='text' id='elem'/>
<input type='button' onclick="notEmpty()" value='Check'/>
</form>
<script type='text/javascript'>
function validate()
{
var patt=/^[0-9]+$/;
var v= document.getElementById('elem').value;
if(v.match(patt))
{
alert("valid entry");
}
else
{
alert("Invalid entry:");
document.getElementById('elem').value="";
document.getElementById('elem').focus();
}
}
</script>
<form>
Required Field: <input type='text' id='elem'/>
<input type='button' onclick="validate()" value='Check'/>
</form>
<script type='text/javascript'>
function validate()
{
var patt=/^[a-zA-Z]+$/;
var v= document.getElementById('elem').value;
if(v.match(patt))
{
alert("valid entry");
}
else
{
alert("Invalid entry:");
document.getElementById('elem').value="";
document.getElementById('elem').focus();
}
}
</script>
<form>
Required Field: <input type='text' id='elem'/>
<input type='button' onclick="validate()" value='Check'/>
</form>
<script type='text/javascript'>
function validate()
{
var minlen=6;
var v= document.getElementById('elem').value;
if(v.length<6)
{
alert("User ID must have at least 6 Characters");
document.getElementById('elem').value="";
document.getElementById('elem').focus();
}
else
{
alert("Valid entry:");
}
}
</script>
<form>
User ID: <input type='text' id='elem'/>
<input type='button' onclick="validate()" value='Check'/>
</form>
<script type='text/javascript'>
function validate()
{
var si=document.getElementById('con').selectedIndex;
var v= document.getElementById('con').options[si].text;
if(v=="Please Choose")
{
alert("You must choose the country");
}
else
{
alert("Your Country is:"+v);
}
}
</script>
<form>
Select Country: <select id='con'>
<option>Please Choose</option> <option>Nepal</option>
<option>India</option> <option>China</option>
</select>
<input type='button' onclick='validate()' value='Check'/>
</form>
<script type='text/javascript'>
function validate()
{
var gender=document.getElementsByName("gen");
if(gender[0].checked==false && gender[1].checked==false)
{
alert("You must choose Gender");
}
else
{
if(gender[0].checked==true)
alert("Male");
else
alert("Female");
}
}
</script>
<form>
Select Gender:
<input type=radio name='gen'>Male
<input type=radio name='gen'>Female
<input type='button' onclick='validate()' value='Check'/>
</form>
Valid Examples:
jagdish@ntc.net
jagdish+bhatta@gmail.com
jagdish-bhatta@patan.edu.np
Invalid Examples:
@deleted.net - no characters before the @
free!dom@bravehe.art - invalid character !
shoes@need_shining.com - underscores are not allowed in the domain name
<script type='text/javascript'>
function validate()
{
var patt=/^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
var v= document.getElementById('elem').value;
if(v.match(patt))
{
alert("valid Email");
}
else
{
alert("Invalid Email"); document.getElementById('elem').value="";
document.getElementById('elem').focus();
}
}
</script>
<form>
Email ID: <input type='text' id='elem'/>
<input type='button' onclick="validate()" value='Check'/>
</form>
As soon as you request a page from a server to which a cookie should be sent, the cookie is added to the
HTTP header. Server side programs can then read out the information and decide that you have the right
to view the page you requested. So every time you visit the site the cookie comes from, information about
you is available. This is very nice sometimes, at other times it may somewhat endanger your privacy.
Cookies can be read by JavaScript too. They're mostly used for storing user preferences.
Examples of cookies:
Name cookie - The first time a visitor arrives to your web page, he or she must fill in her/his name.
The name is then stored in a cookie. Next time the visitor arrives at your page, he or she could get
a welcome message like "Welcome John Doe!" The name is retrieved from the stored cookie
Password cookie - The first time a visitor arrives to your web page, he or she must fill in a
password. The password is then stored in a cookie. Next time the visitor arrives at your page, the
password is retrieved from the cookie
Date cookie - The first time a visitor arrives to your web page, the current date is stored in a
cookie. Next time the visitor arrives at your page, he or she could get a message like "Your last
visit was on Tuesday August 11, 2005!" The date is retrieved from the stored cookie
And so on.
document.cookie:
Cookies can be created, read and erased by JavaScript. They are accessible through the property
document.cookie. Though you can treat document.cookie as if it's a string, it isn't really, and you have
only access to the name-value pairs. If you want to set a cookie for this domain with a name-value pair
'ppkcookie1=testcookie' that expires in seven days from the moment you should write this sentence,
Example:
<html>
<head>
<script type=”text/javascript”>
Function writecookie()
{
If (document.myform.customer.value==” “)
{
alert(“Enter some value”);
return;
}
var cookievalue=document.myform.customer.value + ” ; ”;
document.write (“Setting cookie as:”+”name=”+cookievalue);
}
</script>
</head>
<body>
<form name=”myform”>
Enter name <input type=”text” name=”customer”/>
<input type=”button” value=”setcookie” onlick=”writecookie()”/>
</form>
<body>
</html>