Unit - III (Widt) Pre
Unit - III (Widt) Pre
JavaScript introduction:-
You can insert JavaScript into an HTML page by using <script> tag.
JavaScript is placed between tags starting with <script language=”javascript”> and
ending with </script>.
The script tag attributes are:
language: Scripting language name.
type: Internet content type for a scripting language.
src: URL for an externally linked script.
General syntax of JavaScript is as follows:
<script language=”javascript”>
JavaScript code here……
</script>
1
Different places where JavaScript can be placed in HTML:
<html><head>
<script language=”javascirpt”>
JavaScript written in HEAD section
</script>
</head>
</body>…</body></html>
The general structure for placing JavaScript in the BODY section is:
<html>
<head>…</head>
<body>
<script language=”javascirpt”>
JavaScript written in BODY section
</script>
</body></html>
Basic Rules:
JavaScript programs contain variables, objects, and functions. They key points that
you need to apply in all scripts are listed below:
JavaScript is case sensitive.
JavaScript statements end with semi-colons.
JavaScript has two forms of comments:
Single line comments with a double slash (//) Ex: // this is JavaScript.
Multiline comments begin with “/*” and end with “*/”. Ex: /* multiple lines */
Blocks of code must be surrounded by a pair of curly brackets.
Variables are declared using the var keyword.
2
Functions have parameters which are passed inside parentheses.
<script language=”javascript”>
[Link](“JavaScript is not java”); // JavaScript statement
</script>
Disadvantages of JavaScript:
Security issues: Any JavaScript snippets, while appended onto web pages on client
side immediately can also be used for exploiting the user’s system.
Doesn’t have any multiprocessor or multi threading capabilities.
JavaScript cannot be used for any networking applications.
JavaScript does not allow us to read or write files.
JavaScript render varies: JavaScript may be rendered by different layout engines
differently. As a result, this causes inconsistency in terms of interface and
functionality.
3
3. Explain Variables in JavaScript?
Like many other programming languages, JavaScript has variables. Variables can be
thought of as named containers.
You can place data into these containers and then refer to the data simply by naming
the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are
declared with the var keyword. Ex: var money;
You can also declare multiple variables with the same var keyword.
Ex: var age, ID;
Variables declaration and assignment can be done in a single step.
Ex: var age=34;
4
4. Explain about Data types in JavaScript?
JavaScript provides different data types to hold different types of values. JavaScript
includes data types similar to other programming languages like java or c#.
Data type indicates characteristics of data. It tells the compiler whether the data
value is numeric, alphabetic, data etc.., so that it can perform appropriate
operation. There are two types of data types in JavaScript.
1. Primitive data type 2. Non-primitive (reference) data type
JavaScript is a dynamic type language, means you don't need to specify type of the
variable because it is dynamically used by JavaScript engine.
You need to use var here to specify the data type. It can hold any type of values
such as numbers, strings etc.
Example: var a=30; //holding number
var b="balu"; //holding string
5
DHTML gives more control over the HTML elements. It allows one to incorporate a
client-side scripting language, such as JavaScript, a presentation definition language,
such as CSS, and the Document Object Model in HTML web pages.
HTML DHTML
DHTML stands for Dynamic Hypertext
[Link] stands for Hypertext markup markup language
language
2. HTML is a mark-up language DHTML is a collection of technology.
( HTML, CSS, javascript and DOM).
3. HTML creates static web pages. DHTML creates dynamic web pages,
4. HTML creates a plain page without any DHTML creates a page with HTML, CSS, DOM
styles and Scripts called as HTML and Scripts called as DHTML.
5. HTML sites will be slow upon client-side DHTML sites will be fast enough upon client-
technologies side technologies.
6. HTML cannot have any server side code DHTML may contain server side code.
7. In HTML, there is no need for database DHTML may require connecting to a
connectivity. database as it interacts with user.
8. HTML files are stored with .htm or .html DHTML files are stored with .dhtm
extension extension.
[Link] does not require any processing DHTML requires processing from browser
from browser, which changes its look and feel.
6
varpi_val = [Link];
varsine_val = [Link](30);
Math Methods:
1. abs() : This method returns the absolute value for the given number.
Syntax: [Link](n); where n is a number
Example: var m1=[Link](-21);
[Link](“ The absolute value of -21 is :”+m1);
Result: The absolute value of -21 is: 21
2. sqrt() : This method returns the square root of the given number.
Syntax: [Link](n); where n is a number
Example: var m2=[Link](16);
[Link](“ The square root of 16 is :”+m2);
Result: The square root of 16 is: 4
4. ceil() :This method returns the largest integer for the given number.
Syntax: [Link](n); where n is a number
Example: var m4=[Link](45.89);
[Link](“a ceil value of 45.89 is :”+m4);
Result: aceil value of 45.89 is: 46
5. floor() : This method returns the smallest integer for the given number.
Syntax: [Link](n); where n is a number
Example: var m5=[Link](45.89);
[Link](“a floor value of 45.89 is :”+m5);
Result: afloor value of 45.89 is: 45
7
7. max() : This method returns the largest of zero or more numbers. If no arguments
are given, the results is –Infinity.
Syntax: [Link](valu1,valu2,………,valun); where n is a number
Example: var m7=[Link](50,30,60,90);
[Link](“The maximum value is :”+m7);
Result: The maximum value is: 90
8. min() : This method returns the smallest of zero or more numbers. If no arguments
are given, the results is –Infinity.
Syntax: [Link](valu1,valu2,………,valun); where n is a number
Example: var m8=[Link](50,30,60,90);
[Link](“The maximum value is :”+m8);
Result: The maximum value is: 30
9. sin() :This method returns the sine of a number. The sin method returns a numeric
value between -1 and 1, which represents the sine of the argument.
Syntax: [Link](n); where n is a number
Example: var m9=[Link](90);
[Link](“The sine value of 90 is :”+m9);
Result: The sine value of 90 is: 0.8939966636005578
10. tan() :This method returns the tangent of a number. The tan method returns a
numeric value that represents the tangent of the angle.
Syntax: [Link](n); where n is a number
Example: var m11=[Link](45);
[Link](“The tangent value of 45 is :”+m11);
Result: The tangent value of 45 is: 1
11. log() :This method returns the natural logarithm (base E) of a number. If the value of
number is negative, the return value is always NaN.
Syntax: [Link](n); where n is a number
Example: var m12=[Link](10);
[Link](“The logarithm value of 10 is :”+m12);
Result: The logarithm value of a 10 is: 2.302585092994046
8
varval = new String(string);
The String parameter is a series of characters that has been properly encoded.
String Methods:
1. charAt():charAt() is a method that returns the character from the specified index.
Characters in a string are indexed from left to right. The index of the first character is
0, and the index of the last character in a string, called stringName, is
[Link] –1.
Syntax:[Link](index);
Example:varstr=new String(“Welcome to JavaScript”);
[Link]("[Link](0) is:" + [Link](0));
Result: [Link](0) is: W
2. charCodeAt(): This method returns a number indicating the Unicode value of the
character at the given index. charCodeAt() always returns a value that is less than
65,536.
Syntax:[Link](index);
Example:varstr=new String(“Welcome to JavaScript”);
[Link]("[Link](0) is:" + [Link](0));
Result: [Link](0) is:87
3. indexOf(): This method returns the index position of the given string.
Syntax:[Link](string);
Example:var str1 = new String( "Welcome to JavaScript" );
var index = [Link]( "JavaScript" );
[Link]("indexOf found String is :" + index );
Result: indexOf found String is:11
4. concat():This method adds two or more strings and returns a new single string.
Syntax:[Link](string2, string3, ..., stringN]);
Example:var str1 = new String( "Hello" );
var str2 = new String(" Welcome to JavaScript" );
var str3 = [Link]( str2 );
[Link]("Concatenated String is :" + str3);
Result: Concatenated String is:Hello Welcome to JavaScript
9
[Link]("Lowercase String is :" + str2);
Result: Lowercase String is: welcome to javascript
7. slice():The slice(beginIndex, endIndex) method returns the parts of string from given
beginIndex to endIndex. In slice() method, beginIndex is inclusive and endIndex is
exclusive.
Syntax:[Link](begindex, endindex);
Example:var str1 = new String("welcome to JavaScript" );
var str2 = [Link](3,6);
[Link]("sliced value is :" + str2);
Result: sliced value is: come
8. split() :This method splits a String object into an array of strings by separating the
string into substrings.
Syntax:[Link](separator,limit);
Example:var str1 = new String("welcome to JavaScript let you start" );
var str2 = [Link](“ “,6);
[Link]("splitted value is :" + str2);
Result: splitted value is: welcome, to, JavaScript, let, you, start
9. trim():The JavaScript String trim() method removes leading and trailing whitespaces
from the string.
Syntax:[Link]();
Example:var str1 = new String(" welcome to JavaScript " );
var str2 = [Link]();
[Link]("Trimmed string is :" + str2);
Result: Trimmed string is: welcome to JavaScript
10. substr():This method returns the characters in a string beginning at the specified
location through the specified number of characters.
Syntax:[Link](start, length);
Example:var str1 = new String("welcome to JavaScript ");
var str2 = [Link](3,6);
[Link]("The sub string is :" + str2);
10
Result: The sub string is: come
2. Comparison Operators:
A comparison operator compares its operands and return a logical value based on
whether the comparison is true or not. The comparison operators are listed below
assume variable A holds 10 and variable B holds 20 then:
3. Logical Operators:
These operators are typically used with Boolean (logical) values. They return a
Boolean value. The Boolean operators are listed below, Assume variable A holds 10
and variable B holds 20 Then:
11
Operator Description Example
&& Called logical AND operator. If both the operands (A && B) is true
are non zero then condition becomes true.
|| Called Logical OR operator. If any of the two (A || B) is true
operands are non zero then condition becomes
true
! Called Logical NOT operator. Logical NOT returns !( A && B) is false
false if the operand evaluates to true. Otherwise it
returns true
4. Assignment Operators:
These assignment operators (=) to assign a value to a variable or constant or
expression assigned for given variable. The assignment operators listed below
Operator Description Example
= Assign the value of the right operand to the left C = A + B will assign
operand value of A + B into C
+= Adds together the operands and assigns the result C += A is equivalent to
to the left operand C=C+A
-= It subtracts right operand from the left operand C -= A is equivalent to C
and assigns the result to left operand. =C–A
*= It multiplies right operand with the left operand C *= A is equivalent to C
and assigns the result to left operand. =C*A
/= It divides left operand with the right operand and C /= A is equivalent to C
assigns the result to left operand. =C/A
%= It takes modulus using two operands and assigns C %= A is equivalent to C
the result to left operand. =C%A
5. Bitwise Operators:
The bitwise operators perform bitwise operations on operands. The bitwise
operators are as follows:
6. Conditional Operator (? :)
JavaScript provides conditional operator which is used for comparing two
expressions, also contains a conditional operator that assigns a value to a variable
used on some condition.
Syntax: variable = (condition)? value1:value2;
Example: result = (marks>=35)? “Passed”: “Failed”;
12
Displays result depends on marks, if marks greater than are equal to 35 displays as
passed otherwise failed message.
I. Function Definition:
Before we use a function, we need to define it. The most common way to define a
function in JavaScript is by using the function keyword, followed by a unique function name,
a list of parameters (that might be empty), and a statement block surrounded by curly
braces.
Syntax:
function function_Name(parameters list)
{
//code to be executed
}
Example:
function sayHallo()
{
Alert(“Hello there”);
}
13
</script>
</head>
<body>
<form>
<input type="button" onclick="sayHello()" value="Say Hello">
</form>
</body>
</html>
14
10) Explain Conditional statements (Decision making) in JavaScript?
Conditional statements are used to perform different actions based on different
conditions. In JavaScript we have the following conditional statements.
I. If statement:
A if statement is used to execute some code if only, if specified conditions is true.
Syntax:
if (condition)
{
Code to be executed if condition is true
}
Example:
<html>
<head>
<title>If Statement</title></head>
<body>
<script type="text/javascript">
var age=20;
if(age>=18)
{
[Link](" You are eligible to vote ");
}
</script></body></html>
Output: You are eligible to vote
15
<script type="text/javascript">
var age=20;
if(age>=18)
{
[Link](" You are eligible to vote ");
}
else
{
[Link](" You are not eligible to vote ");
}
</script></body></html>
Output: You are eligible to vote
III. If-else-if statement (else if ladder):
An if-else-if statement is used to select one of several blocks of code to be executed.
Syntax:
if (condition1)
{
Code to be executed if condition1 is true
}
else if (condition2)
{
Code to be executed if condition2 is true
}
else if (conditionN)
{
Code to be executed if conditionN is true
}
else
{
Code to be executed if condition1 and 2 are not true
}
Example:
<html>
<head><title>If else if Statement</title></head>
<body>
<script type="text/javascript">
var marks=65;
if(marks>=75)
{
[Link](" Distinction");
16
}
else if (marks>=60 && marks<75)
{
[Link](" First division");
}
else if (marks>=50 && marks<60)
{
[Link](" Second division");
}
else if (marks>=40 && marks<50)
{
[Link](" Third division");
}
else
{
[Link](" Fail");
}
</script></body></html>
Output: First Division
17
<script type="text/javascript">
var grade=A;
switch (grade)
{
case ‘O’: [Link](" Out Standing”);
break;
case ‘A’: [Link](" Excellent”);
break;
case ‘B’: [Link](" Good”);
break;
case ‘C’: [Link](" Very Good”);
break;
case ‘D’: [Link](" Fair”);
break;
default: [Link](" Fail”);
break;
</script></body></html>
Output: Excellent
I. For loop:
The JavaScript for loop iterates the elements for the fixed number of times. It
should be used if number of iteration is known.
Syntax:
for (initialization; condition; increment)
{
code to be executed
}
Example:
<html>
<head><title>For Loop Statement</title></head>
<body>
<script type=”text/javascript”>
for (var i=1; i<=5; i++)
{
18
[Link](i + "<br/>") ;
}
</script></body></html>
Output: 1 2 3 4 5
Example:
<html>
<head><title>While Loop Statement</title></head>
<body>
<script type=”text/javascript”>
var i=0;
while (i<=5)
{
[Link](i + "<br/>")
}
</script></body></html>
Output: 1 2 3 4 5
Example:
<html>
19
<head><title>do while Loop Statement</title></head>
<body>
<script type=”text/javascript”>
var i=0;
do
{
[Link](i + "<br/>")
}
while (i<=5);
</script></body></html>
Output: 1 2 3 4 5
JavaScript provides full control to handle loops and switch statements. There may
be a situation when you need to come out of a loop without reaching its bottom.
There may also be a situation when you want to skip a part of your code block and
start the next iteration of the loop.
To handle all such situations, JavaScript provides break and continue statements.
These statements are used to immediately come out of any loop or to start the
next iteration of any loop respectively.
break and continue statements are used in for, while and do while loops.
I. Thebreak Statement:
The break statement, which was briefly introduced with the switch statement, is
used to exit a loop early, breaking out of the enclosing curly braces.
Syntax: break;
Example:
<html>
<head><title>Break statement</title></head>
<body>
<script type="text/javascript">
var i;
for(i=0;i<=5;i++)
{
if(i==4)
{
break;
}
[Link](i+"<br>");
20
}
</script></body></html>
Output: 0 1 2 3
The Array object lets you store multiple values in a single variable. It stores a fixed-
size sequential collection of elements of the same type.
An array is used to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type.
There are 3 ways to construct array in JavaScript
By array literal:
The syntax of creating array using array literal is given below:
Syntax: var arrayname=[value1,value2 .... valueN];
As you can see, values are contained inside [ ] and separated by, (comma).
Example:
<html>
<script>
var emp=["Balu","Chiru","Raja"];
for (i=0;i<[Link];i++){
21
[Link](emp[i] + "<br/>");
}
</script>
</html>
Output: Balu
Chiru
Raja
22
Output: Balu
Chiru
Raja
A JavaScript object is an entity having state and behaviour (properties and method).
For example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is an object-based language. Everything is an object in JavaScript.
JavaScript is template based not class based. Here, we don't create class to get the
object. But, we direct create objects.
Javascript provides a number of application objects such as the document, window,
string, math, array, number and date objects.
Each object has properties that can be read and sometimes setting JavaScript
statements. Many Objects have methods such as [Link] () that give the
object significant functionality.
Creating Objects: - There are three ways to create objects in JavaScript.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
1. By object literal:-
The syntax of creating object using object literal is given below:
object ={property1:value1,property2:value2.... propertyN:valueN}
As you can see, property and value is separated by : (colon).
Example: -
<html>
<script language="javascript">
emp={ id:102,name:"Subbu",salary:40000 }
[Link]([Link]+" "+[Link]+" "+[Link]);
</script>
</html>
Result: - 102 Subbu 40000
23
var emp=new Object();
[Link]=101;
[Link]="Priyadarsini";
[Link]=50000;
[Link]([Link]+" "+[Link]+" "+[Link]);
</script> </html>
Result: - 102 Priyadarsini 50000
24
Setting the properties of an Object: It is also possible to assign values to some
object properties. So while it doesn’t make sense to be able to change the
location where the document came from, you can change the background color
of the document this way:
[Link]=”#800080”;
[Link]=”Orange”;
Methods: -
Methods are a way of asking an object to do something more complicated than
changing a property.
There is a small difference between a function and a method – at a function is a
standalone unit of statements and a method is attached to an object and can be
referenced by the this keyword.
Methods are useful for everything from displaying the contents of the object to
the screen to performing complex mathematical operations on a group of local
properties and parameters.
Following is a simple example to show how to use the write() method of
document object to write any content on the document.
[Link](“JavaScript Expression”);
Here write() is a method (a function) that belongs to the document object. Calling
write() is like asking a document to append HTML to itself. The javascript
expression inside the round brackets will be evaluated and the result (whatever it
is) written out to the HTML page.
Here are some more methods for the document object:
close(), open(), writeln(), getElementById(“ID”)
Example: -
<script type="text/javascript">
var book = new Object(); // Create the object
[Link] = "Web Technology"; // Assign properties to the object
[Link] = "Balu";
</script></head>
<body>
<script type="text/javascript">
[Link]("Book name is : " + [Link] + "<br>"); // Using write() Method
[Link]("Book author is : " + [Link] + "<br>"); // Using write() Method
</script></body>
Result: -
Book name is : Web Technology
Book name is : Balu
25
16) What is Regular Expression? Explain how to create Regular Expressions.
Regular Expressions are very powerful tools for performing pattern matches.
You can perform complex tasks that once required lengthy procedures with just a
few lines of code using regular expressions.
A Regular Expressions is an object that describes a pattern of characters. Regular
Expressions are used to perform pattern-matching and search-and-replace
functions on text.
Regular Expressions are implemented in two ways:
Using Literal.
Using RegExp() constructor.
The literal syntax looks something like:
var RegularExpression= /pattern/attributes;
The RegExp() constructor method looks like:
var RegularExpression= new RegExp(“pattern”,”attributes”);
pattern: - A string that specifies the pattern of the regular expression or another
regular expression.
attributes : - An optional string containing any of the "g", "i", and "m" attributes
that specify global, case-insensitive, and multiline matches, respectively.
RegExp() Object methods: -
Regular expressions are used with the RegExp methods test() and exec() and with
the String methods match(), replace(), search(), and split().
test() : A RegExp method that tests for a match in a string. It returns true or
false. The test() method syntax is : [Link](str);
exec() : A RegExp method that executes a search for a match in a string. It
returns an array of information or null on a mismatch.
match() : A String method that executes a search for a match in a string. It
returns an array of information or null on a mismatch.
search() : A String method that tests for a match in a string. It returns the
index of the match, or -1 if the search fails.
replace() : A String method that executes a search for a match in a string,
and replaces the matched substring with a replacement substring.
split() : A String method that uses a regular expression or a fixed string to
break a string into an array of substrings.
Example:
<html>
<head>
<title>JavaScript RegularExpressions</title>
</head>
<body>
<script type="text/javascript">
var str = "Javascript is an interesting scripting language";
26
var rem = new RegExp( "script", "g" );
var result = [Link](str);
[Link]("Test 1 - returned value is : " + result);
rem = new RegExp( "pushing", "g" );
var result = [Link](str);
[Link]("<br />Test 2 - returned value is : " + result);
</script>
</body>
</html>
Result:
Test 1 - returned value is : script
Test 2 - returned value is : null
27
Block of code to be executed regardless of the try / catch result
}
Example:
<html>
<head>
<script type="text/javascript">
function myFunc()
{
var a = 100;
var b = 0;
try{
if ( b == 0 )
{
throw( "Divide by zero error." );
}
else
{
var c = a / b;
}
}
catch ( e )
{
alert("Error: " + e );
}
}
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
Token Description
^ Match at the start of the input string
$ Match at the end of the input string
28
* Match 0 or more items
+ Match 1 or more items
? Match 0 or 1 time
a/b Match a or b
{n} Match the string n times
\d Match a digit
\D Match anything except for digits
\w Match anything alphanumeric characters or the underscore.
\W Match anything except alphanumeric characters or the underscore.
\s Match a whitespace character.
\S Match anything except for whitespace characters.
\t Matches horizontal characters.
[xyz] Match any one character enclosed in the character set ex: /[0-9]/
() Grouping characters together to create a clause.
29
{
if( [Link] == "" )
{
alert( "Please provide your name!" );
[Link]();
return false;
}
if( [Link] == "" )
{
alert( "Please provide your Password!" );
[Link]();
return false;
}
return (true);
}
</script>
</head>
<body>
<form action="/action_page_post.php" name="f1"
onsubmit="return(validate());">
UserName: <input type="text" name="UserName" /><br><br>
Password: <input type="text" name="Password" ><br><br>
<input type="submit" value="Submit" />
</form>
</body></html>
Result:
30
20) Explain how to open a new window in JavaScript?
Web browsers are based around a different model in which each new window is
independent of the application from which it was launched.
Majority of the JavaScript coding is based using windows.
The application has a single global frame and when new windows are opened they
appear inside the frame.
The application frame is said to be the parent of all of the internal frames.
The following features are available in most browsers:
toolbar=1|0 : Specifies whether to display the toolbar in the new window.
location=1|0 : Specifies whether to display the address line in the new
window.
directories=1|0 : Specifies whether to display the Netscape directory buttons.
status=1|0: Specifies whether to display the browser status bar.
menubar=1|0 : Specifies whether to display the browser menu bar.
scrollbars=1|0 : Specifies whether the new window should have scrollbars.
resizable=1|0 : Specifies whether the new window is resizable.
width=pixels : Specifies the width of the new window.
height=pixels : Specifies the height of the new window.
Example:
<html>
<head>
<title>Opening New Window</title>
</head>
<script type="text/javascript">
function load()
{
var myWindow = [Link]("
[Link] "myWindow",
"location=1, status=1, scrollbars=1, width=500, height=300");
}
</script>
<body onload="load()">
<h1>JavaScript New window Opening</h1>
</body></html>
Result:
31
21) Explain about messages and confirmations (Dialog boxes or Pop-up boxes)
in JavaScript?
JavaScript provides three built-in window types that can be used from application
code. These are useful when you need information from visitors to your site.
For instance you may need them to click a confirmation button before submitting
information to your database.
Three kinds of popup boxes created using JavaScript are:
Alert box
Confirm box
Prompt box
1. Alert Box:
The alert box is useful for alerting the users to something important.
When a Javascript alert box triggered, a small box will pop up the text that is
specified in the Javascript code.
The alert box pops up with an ok button which the user has to press to continue.
Syntax: alert(“text message”);
Example:
<html>
<head>
<title> alert box Example</title>
</head>
<body>
<script type="text/javascript">
function display()
{
alert("This is an alert box");
}
</script>
<input type="button" value="click me!" onclick="display()"/>
</body>
</html>
Result:
32
2. Confirm box:
The confirm method shows a dialog box that contains a message and an ok and
cancel button.
If the user presses the ok button the confirm method returns true.
If the user presses cancel button return false.
Syntax: confirm(“text message”);
Example:
<html>
<head><title> Confirm box Example</title>
</head>
<body>
<script type="text/javascript">
var x= confirm("if you do hardwork");
if(x)
alert(" You will get good marks ");
else
alert(" You will get less marks ");
</script></body></html>
Result:
3. Prompt box:
The prompt method shows a dialog box with a message, a text entry field, an ok
button, and a cancel button.
If the user presses ok the text in the test entry field is returned as a string.
If the user presses cancel the null value is returned by the prompt method.
33
Prompt takes two parameters. The first is a message (or instructions) and the
second default text that will appear in the text entry field.
Syntax: prompt(“ Text message”, “Default value”);
Example:
<html>
<head><title> Prompt box Example</title>
</head>
<body>
<script type="text/javascript">
var age= prompt("Enter your age","18");
if(age>=18)
alert(" you are eligible to vote ");
else
alert(" you are not eligible to vote ");
</script></body></html>
Result:
Javascript Events: -
34
Event Description
onclick The event occurs when the user clicks on an element
ondblclick The event occurs when the user double-clicks on an element
onmouseover The event occurs when the pointer is moved onto an element, or
onto one of its children
onmouseout The event occurs when a user moves the mouse pointer out of an
element, or out of one of its children
onmouseup The event occurs when a user releases a mouse button over an
element
onmousedown The event occurs when the user presses a mouse button over an
element
onload The event occurs when an object has loaded
onunload The event occurs once a page has unloaded (for <body>)
onsubmit The event occurs when a form is submitted
onfocus The event occurs when an element gets focus
onselect The event occurs after the user selects some text (for <input> and
<textarea>)
onkeypress The event occurs when the user presses a key
Example:
<html>
<head>
<title>Event Handling</title>
</head>
<body onLoad="ShowLoaded()" onunload="SayGoodbye()">
<h1> handling events</h1>
<a href="#" onMouseOver="Mouse()"> A Hyperlink</a><br >
<form>
<input type="button" value="ClickMe!"
onclick="Clicked()"onmouseover="Mouse">
</form>
<script language="javascript">
function ShowLoaded()
{
alert("The page has loaded");
}
function SayGoodbye()
{
alert("Goodbye, thank u for visiting");
}
35
function Clicked()
{
alert("you clicked the button");
}
function Mouse()
{
alert("the mouse is over the link");
}
</script></body></html>
36
close(), getElementById(“ID”), open(), write(“string”), writeln(“string”).
3. Browser (Navigator) object: - The browser object is a JavaScript object and can be
queried from within your code. The browser object is actually called the navigator
object.
Syntax: -
[Link]; (or) [Link](parameters);
Properties: - The following properties of navigator object are:
appCodeName, appname, appVersion, language, userAgent, plugins, cookieEnabled and
platform.
Methods: - The following methods of navigator object are:
javaEnabled(), taintEnabled().
4. Date Object: - The JavaScript date object can be used to get year, month and day. You
can display a timer on the webpage by the help of JavaScript date object.
You can use different Date constructors to create date object. It provides methods
to get and set day, month, year, hour, minute and seconds. You can use 4 variant of
Date constructor to create date object.
1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)
Syntax:
var today=new Date();
Properties: - The following properties of date object are:
Constructor and prototype.
Methods: - The following methods of Date object are:
date(), getDate(), getDay(), getMonth(), getYear(), setTime(), setDate(), setMonth()
and setHours(),…etc,.
37
5. History Object: - The JavaScript historyobject represents an array of URLs visited by
the user. By using this object, you can load previous, forward or any particular page.
Syntax:
[Link]; (or) [Link]();
Properties: - The following properties of history object are:
length, next, previous and current.
Methods: - The following methods of history object are:
forward(), back() and go().
6. Form Object: - The JavaScript Form Object is a property of the document object. This
corresponds to an HTML input from constructed with the FORM tag. A form can be
submitted by calling the JavaScript submit method or clicking the form submit
button. The Form object represents an HTML <form> element.
Syntax:
var x = [Link]("myForm");
Properties: - The following properties of form object are: action, target, name,
method, validate, onsubmit, length and encoding.
Methods: - The following methods of form object are:
reset() and submit().
38
[Link](“[Link] = “+[Link]+”<br”>);
[Link](“[Link] = “+[Link]+”<br”>);
[Link](“[Link] = “+[Link]+”<br”>);
</script>
Example 2:
It displays the confirm dialog box. It has message with ok and cancel buttons.
<script type="text/javascript">
function msg(){
var v= confirm("Are u sure?");
if(v==true){
alert("ok");
39
}
else{
alert("cancel");
}
}
</script>
<input type="button" value="delete record" onclick="msg()"/>
Example 3:
It displays prompt dialog box for input. It has message and text field.
<script type="text/javascript">
function msg(){
var name= prompt("Who are you?");
alert("I am "+name);
}
</script>
<input type="button" value="click" onclick="msg()"/>
40
getMilliseconds(): It returns all the elements having the given tag name.
Example:
<script language=”javascript”>
var date=new Date();
var day=[Link]();
var month=[Link]()+1;
var year=[Link]();
[Link]("<br>Date is: "+day+"/"+month+"/"+year);
[Link](“<br>Hours is: “ + [Link]());
[Link](“<br>minuts is: “ + [Link]());
</script>
41
[Link]: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
[Link]: Win32
[Link]: true
42
The lower frame shows the result of the color selections but has been created by
JavaScript code.
This application is run totally on the client side.
The frameset:
The whole page is built around a simple frameset. When the page is initially loaded
it displays the form in the upper window (top) And an empty html page in the
lower window (bottom).
Example:
<html><head>
<title> Addition of two Numbers</title>
</head>
<frameset rows="50%,*">
<frame name="top" src="[Link]">
<frame name="bot" src="[Link]">
</frameset>
</html>
Here is the code for empty frame ([Link]):
<html>
<head>
<title>Empty Frame</title>
</head>
<body>
</body></html>
The Upper Frame ([Link]):
<html>
<head>
<script language="javascript">
function Addition()
{
var t=[Link][0].elements;
var b=[Link]['bot'].document;
var a1=[Link];
var a2=[Link];
var c=parseInt(a1)+parseInt(a2);
[Link]();
[Link]("The Result is:"+c);
[Link]();
}
</script>
</head>
<body bgcolor="pink" text="green">
43
<h1 align=center> Addition of Two numbers</h1>
<form ><center>
Enter the value of a : <input type="text" name="n1"><br>
Enter The value of b : <input type="text" name="n2"><br>
<input type="button" value="Add" onclick="Addition();">
<input type="button" value="Reset It">
</form></body></html>
Result:
44
Result:
45
46