Wt-Unit-3 (Javascript)
Wt-Unit-3 (Javascript)
Unit-III
Introduction To JavaScript
1. What is DHTML?
DHTML means Dynamic Hypertext Markup Language
DHTML is NOT a language.
DHTML is a TERM describing the art of making dynamic and interactive web pages.
DHTML combines HTML, JavaScript, the HTML DOM, and CSS.
III BSc,SEMESTER-6,PAPER-7Web-Technologies
5. What are the alternatives of Java Script?
Java script is a powerful scripting language. There are lot of alternative scripting
languages are available now. Those are
JScript (Microsoft)
VBScript (Microsoft)
PHP (While PHP originally stood for Personal Home Page, it is now said to stand for
PHP: Hypertext Preprocessor)
CGI (Common Gateway Interface)
Dart (Google)
GWT or Google Web Toolkit is a framework for developing client-side web applications
using Java.
6. Explain the structure of a Java Script program & explain how it is include in html
documents
Java script code resembles C language. The key points that you need to apply in all
scripts are listed below.
Each line of code is terminated by a semicolon.
Block of code must be surrounded by a pair of curly braces.
A block of code is a set of instructions that are to be executed together as a unit.
Functions have parameters, which are passed inside parenthesis.
Variables are declared using a keyword var.
Scripts require neither a main function nor an exit condition.
Execution of a script starts from the first line of code and runs to the last line of code.
Including Java Script into on HTML document:
We can include script in a web page in two ways.
Way 1: if your script code is very small directly include in the pair of <HTML></HTML> tags
directly.
Ex:
<html>
<head>
<script type = “text/Javascript”> Code related to java script</script>
</head>
<body>
……..
III BSc,SEMESTER-6,PAPER-7Web-Technologies
……..
</body>
</html>
Way 2: If your scripts are complex, then write script language in a separate file and save it a
“filename. js” and include it in a separate HTML document as follow.
Ex:
<html>
<head>
<script type = “text/javascript” src= “filename.js”/>
</head>
<body>
……..
</body></html>
viii. Index of (“Search” [, offset]): The string is searched for the string or quoted characters in
the first parameter. If the search is successful the index of the start of the target string is returned
otherwise it returns -1. The function starts search from the start of the string (offset=0) offset
may also be specified as argument.
Ex: var name = “TJPS College, Guntur”;
Var result= name.IndexOf(“Col”);
if(result==-1)
document.writeln(“String not found”);
else
document.writeln(“String found”);
v. Cos (value), sin (value), tan (value): It returns the Cosine, Sine, and Tangent values of
the values passed respectively.
vi. Log (value): It returns the natural logarithmic value of its argument.
vii. Max( val1, val2): It returns the biggest of the two passed values.
III BSc,SEMESTER-6,PAPER-7Web-Technologies
Ex: var itemMax = Math.max(3, 54, 32, 16);
alert(itemMax); //outputs “54”
viii. Min( val1, val2): It returns the smallest of the two passed values.
Ex: var itemMin = Math.min(3, 54, 32, 16);
alert(itemMin); //outputs “3”
ix. ParseInt(string[index]): It returns integer equivalent of the string passed in.
x. ParseFloat(string): It returns floating point number equivalent of the string passed in.
xi. POW(value power):The pow() method is used to raise a number to a given power, such
as raising 2 to the power of 10.
Ex: variNum = Math.pow(2, 10);
xii. Random(): It returns a pseudo random number between 0 and 1.
xiii. Round(value): It returns result of rounding its argument to the nearest integer.
Ex: alert(Math.round(25.5)); //outputs “26”
xiv. Sqrt(value): It returns the square root of the value passed in.
Ex: var itemNum = Math.sqrt(4);
alert(itemNum); //outputs “2”
Ex: if(hour<12)
{
document.write(“Good morning”);}
III BSc,SEMESTER-6,PAPER-7Web-Technologies
The syntax of the second form of the if statement is similar to the firm form except that
an else clause is added.
Syn:
If(condition)
{
First set of statements;
}
else {
Second set of Statements ;
}
Ex:
If(hour<12) {
document.write(“Good Morning”);
} else
{ document.write(“Hello
”);
}
The Switch Statement:
The syntax of the switch statement as follows.
Switch(expression)
{
Case value1:
Statements
Break;
………………………..
………………………..
Case valuen:
Statements
Break;
Default:
Statements
}
III BSc,SEMESTER-6,PAPER-7Web-Technologies
The switch statement evaluates the expression and determines if any of the values
(value1 through value n) match the expression’s value. If one of them matches, then the
statements for that particular case are executed, and statement execution then continues after the
switch statement. If there is not matching value, then statements for the default case are
executed.
Ex:
<html>
<head> <title> Using the switch statement </title> </head>
<body>
<script type=”text/javascript”>
for(i=1;i<=3;++i)
{
Switch(i) {
Case 1:
Val=”One”; break;
Case 2:
Val=”Two”; break;
Case 3:
Val=”Three”; break;
Case 4:
Val=”Four”; break;
Case 5:
Val=”Five”; break;
default:
Val=”Unkown”;
}
document.writeln(Val + “<br>”);
}
</script>
</body>
</html>
III BSc,SEMESTER-6,PAPER-7Web-Technologies
11. Illustrate the Loop Statements in Java Script with suitable example?
Loop statements are used to repeat the execution of a set of statements while a particular
condition is true. JavaScript supports three types of loop statements: the While statement, the
do-while statement, the for statement.
The While Statement:
The While statement is a basic loop statement, used to repeat the execution of a set of
statements while a specified condition is true.
Syn:
while ( condition ) {
statements
}
Ex:
<html>
<head><title> Using While
Statement</title></head> <body>
<script type=”text/JavaScript”>
i=1;
while(i<7)
{
document.write(“<H” +i+ ”> This is a level “+i+” heading.
<H”+i+”>”); ++i;
}
</script>
</body></html>
Logical Operators:
Logical operators are used to perform Boolean operations on Boolean operands, such as
logical and, logical or, and logical not. The logical operators supported by JavaScript as
follows.
Operator Description
& Logical And
||Logical or
!Logical not
KADIRI NAGESWARA RAO M.C.A Department of Computer Science, T.J.P.S College, Guntur.
12
III BSc,SEMESTER-6,PAPER-7Web-Technologies
Comparison Operators:
Comparison operators are used to determine whether two values are equal, or to compare
numerical values to determine which value is greater than the other.
Operator Description
= Equal
= Strictly equal
!= Not equal
!== Strictly not equal
< Less than
<= Less than or equal
> Greater than
>_ Greater than or equal
String Operators:
String operators are used to perform operations on strings. Java script currently supports
only the +string concatenation operator. It is used to join two strings together.
Other operators are *=, /=, %=, <<=, >>=, >>>=, &=, !=, ^=
The conditional Expression Ternary Operator:
The ternary operator takes three operands – a condition to be evaluated and two
alternative values to be returned based on the truth or falsity of the condition.
Condition ? value1 : value2
Special Operators:
i. The comma (,) operator:
This operator evaluates two expressions and returns the value of the second expression.
ii. The delete operator:
The delete operator is used to delete a property of an object or an element at an array
index.
iii. The new operator:
The new operator is used to create an instance of an object type.
iv. The Typeof operator:
The typeof operator returns a string value that identifies the type of an operand.
Access an Array:
We can refer to a particular element in an Array by referring to the name of the Array and
the index number. The index number starts at 0.
Ex: document.write(a[0]);
</body>
</html>
KADIRI NAGESWARA RAO M.C.A Department of Computer Science, T.J.P.S College, Guntur.
17
III BSc,SEMESTER-6,PAPER-7Web-Technologies
Return statement:
The return statement is used to specify the value that is returned from the function.
Example:
<html>
<head>
<script type=”javascript”>
function Add (a,b)
{
return a+b;
}
</script>
</head>
<body>
<script type=”javascript”>
document.write(add(30,55));
</script></body></html>
do something
if an error happens
{
create a new exception object
III BSc,SEMESTER-6,PAPER-7Web-Technologies
throw the exception
}
Try….. catch:
A program is going to try to execute a block of statements. If exception is thrown by any
of those statements, execution of the whole block ceases and the program looks for a catch block
ceases and the program looks for a catch statement to handle the exception. try
{
Statement one
Statement two
Statement three
}
catch exception
{
Handle the exception
}
I BSc,SEMESTER-6,PAPER-7Web-Technologies
OBJECTS IN THE JAVA SCRIPT
1. How java Script supports object orientation?
JavaScript is not a complete programming language but, rather, it is a scripting language.
There are some object-oriented features that are not supported by JavaScript. JavaScript does not
support the features of inheritance, information hiding, encapsulation and classification that are
supported by other object-oriented programming languages.
Object based features supported by JavaScript:
It supports various features related to object based language and JavaScript is sometimes
referred to as an object-based programming language. The vital features which JavaScript
supports related to object based are:
Object Type:
JavaScript supports the development of object types and in this context JavaScript
supports both predefined and user-defined objects. It is possible to assign objects of any type to
any variable.
Object Instantiation:
To carry out the process of creating specific object instances available in JavaScript,
users can make use of a new operator. The object types are defined by properties and methods.
Properties of objects are used to access the data values contained in an object.
2. What are Regular Expressions and explain the creation of regular expressions in Java
Script?
Regular expressionsare very powerful tools for performing pattern
matches.We use regular expressions to search for matches on particular text.
In JavaScript, we can use regular expressions by creating instances of the regular
expressionobject, RegExp.
Creating Regular Expressions:
Regular expressions can be creating in two ways those are statically (when the script is
first parsed) and dynamically (at run-time).
The RegExp() method allows you to dynamically construct the search pattern as a string, and is
useful when the pattern is not known ahead of time.
Example: & Exercise:
<html>
<head>
<title> Regular Expression Example</title>
<script Type="text/JavaScript">
function checkpincode()
{
var re6digit=/^\d{6}$/
var str= document.myform.myinput.value;
if (str.search(re6digit)==-1)
alert("Please enter a valid 6 digit number inside form");
else
alert("Entered value is correct");
}
</script>
</head>
<body>
<form name="myform">
Enter valid Pincode (6 digits) : <input type="text" name="myinput"
size=15> <input type="button" onClick=" checkpincode()" value="check">
</form>
</body>
</html>
var re6digit=/^\d{5}$/
^ indicates the beginning of the string. Using a ^ metacharacter requires that the match start
at the beginning.
\d indicates a digit character and the {5} following it means that there must be 5 consecutive
digit characters.
$ indicates the end of the string. Using a $ metacharacter requires that the match end at the
end of the string.
JavaScript Regular Expressions have the following methods and properties.
2.RegExp.test(string): Tests if the given string matches the Regexp, and returns true if
matching, false if not.
KADIRI NAGESWARA RAO M.C.A Department of Computer Science, T.J.P.S College, Guntur.
23
III BSc,SEMESTER-6,PAPER-7Web-Technologies
iv. referrer: URL of the page from which the user came
v. bgColor: hexadecimal representation of the page color.
vi. fgColor: hexadecimal representation of the text colour for the current page.
vii. linkColor, alinkColor, vlinkColor: hexadecimal representation of the colours used for
links
viii. forms[]: Array of forms on the current page.
ix. forms.length: the number of form objects on the page.
x. links[]: Array of links from the current page in the order in which they appear in the
document.
xi. links.length: the number of hyperlinks on the page.
xii. anchors[]: an array of named anchors (internal links)
xiii. anchors.length: number of anchors in the document.
xiv. images[], applets [], embeds[]: Array of images, Java applets and plug-in objects on the
current page.
Methods:
i. write(“String”): It writes an arbitrary string to the HTML document.
ii. writeln(“String”): It writes a string to the HTML document and terminate it with a new
line character.
iii. Clear(): It clears the current document.
iv. Close: It closes the document.
KADIRI NAGESWARA RAO M.C.A Department of Computer Science, T.J.P.S College, Guntur.
24
III BSc,SEMESTER-6,PAPER-7Web-Technologies
viii. defaultStatus: It sets the default message for the status bar.
ix. name:The name of the window if it was created using the open() method and a name was
specified.
Methods:
i. alert(‘String”): It open a box containing the message.
ii. blur(): It remove focus from current window
iii. confirm(“String”):It displays a message box with OK and Cancel buttons.
iv. focus(): It give focus to current window
v. prompt(“String”): It displays a prompt window with field for the user to enter a text
string.
vi. scroll(int, y): It move the current window to the chosen x,y location.
vii. open(“URL”, “name”, “Options string”):It opens a new window showing the page at
URL. The window is given the name of parameter two and its appearance may be
controlled by the options list.
viii. close(): It close the current window
iii. The Form object
Form object can be manipulated in two ways by using JavaScript. The data that is entered
onto your form can be checked at submission. Second we can actually build forms through
JavaScript.
Properties:
name: the unique name of the form
method: submission method in numeric form. 0 = GET, 1 = POST
action: the action attribute of the form.
target: if specified this is the target window for responses to the submission of the form.
elements[]: an array containing the form elements in the order in which they are declared
in the document.
length: the number of elements in the form.
Methods:
submit(): it submits the form.
reset(): it resets the form.
Event Handlers:
onSubmit(method): actions to be performed as the form is submitted.
onReset(method): any actions to perform as the form is reset.
KADIRI NAGESWARA RAO M.C.A Department of Computer Science, T.J.P.S College, Guntur.
25
III BSc,SEMESTER-6,PAPER-7Web-Technologies
Ex:
<html>
<head>
<script type = "text/javascript">
function validate()
{
var method = document.forms[0].method;
var action = document.forms[0].action;
var value = document.forms[0].elements[0].value;
if ( value != "Narasimha")
{
document.forms[0].reset();
}
else
{
alert ("Hai ");
}
}
</script>
</head>
<body>
<form method = "post">
<input type = "text" name = "user" size = "32" >
<input type = "submit" value = "press me"
onClick = "validate()">
</form>
</body></html>