Introduction To JavaScript-1
Introduction To JavaScript-1
History of JavaScript
Features of JavaScript
1. JavaScript is an Object based language that is confined to run within the web
browsers only.
2. JavaScript is an interpreted language and requires no compilation steps.
3. JavaScript can directly be embedded in HTML files. The Html files with
embedded JavaScript commands interpreted by browser that is JavaScript enabled.
4. JavaScript is loosely typed language i.e. one data type can be automatically
converted into other types without explicit conversion.
5. JavaScript is platform independent but browser dependent. The JavaScript
applications work on any machine that has an appropriate JavaScript enabled
browser installed.
6. A scripting language is a lightweight programming language
7. JavaScript supports event-base programming.
8. Performance is good since the JavaScript programs are included in the same file
as the HTML code for a web page, the download time for the client minimum.
JavaScript code is executed from within HTML Documents. So your WebPages will
not only contain HTML tags, but also the JavaScript statements (called scripts).
There are two ways to insert JavaScript Code into an HTML file.
1. One way to insert JavaScript Code is to embed it directly within the <script> and
</script> tag pair. The <script> tag notifies the browser that everything contained
within is script and is to be interpreted by a suitable interpreter.
JavaScript code
</script>
The optional attribute language specifies the programming language used for
scripting. there are many languages available in the market for scripting. common
languages are javascript and VBscript.. this attribute basically instructs the browser
which interpreter to use for interpretation. If nothing is specified JavaScript is
assumed by the browser
2. Another way to insert JavaScript Code is to place it in the external source file
and refer to it from an HTML file. This external source file generally has extension
.js. a source file contains only JavaScript Statements without any script tag or
other HTML tags. The tag <script> has the attribute src, which may be used to
refer top the external JavaScript Source file.
When using a javaScript file, the browser ignores any javaScript Statements within
the <script> and </script> tags. So do not write anything between the opening and
closing <script> tag.
If the JavaScript Code is fairly lang. it is easy to use the source file. It has many
distinct advantages.
1. This makes the HTML file neater and cleaner. Too much javaScript Code
makes it large and unreadable.
2. The same JavaScript Source file can be reused in many HTML files.
3. The JavaScript code remains hidden if the browser is not compatible with it.
Incompatible embedded JavaScript code is displayed as if it is normal text.
Placement of javaScript
/* sample program*/
<html>
<head>
<script language="javascript">
[Link]("welcome to java script");
</script>
</head>
<body>
</body>
</html>
Adding comments
1. Line comments
Line comments starts with //. The entire line is treated as comment line and is
skipped.
Eg: // this is a line comment and it will be ignored
2. Block comments
A block comment stats with /* and ends with */. Everything within theses
opening and closing character sequence is ignored.
Eg:
/*
This is a block comment
This will also be ignored
*/
Javascript keywords
A variable declared without the keyword var is always a global variable and the
variables which precede with var keyword are called local variables. This allows us
to create a global variable from within a function.
Eg:
JavaScript Literals are constant values that can be assigned to the variables that are
called literals or constants. JavaScript Literals are syntactic representations for different
types of data like numeric, string, Boolean, array, etc data. Literals in JavaScript provide
a means of representing particular or some specific values in our program. Consider an
example, var name = “john”, a string variable named name is declared and assigned a
string value “john”. The literal “john” represents, the value john for the variable name.
There are different types of literals that are supported by JavaScript.
1. Integer Literals
Integer literals are numbers, must have minimum one digit (0-9). No blank or comma is
allowed within an integer. It can store positive numbers or negative numbers. In integers,
literals in JavaScript can be supported in three different bases.
1. The base 10 that is Decimal (Decimal numbers contain digits (0,9) ) examples for
Decimal numbers are 234, -56, 10060.
2. Second is base 8 that is Octal (Octal numbers contains digits (0,7) and leading 0
indicates the number is octal), 0X 073, -089, 02003.
3. String Literals
A string literals are a sequence of zero or more characters. A string literals are either
enclosed in the single quotation or double quotation as ( ‘ ) and ( “ ) respectively and to
concatenate two or more string we can use + operator. Examples for string are “hello”,
“hello world”, “123”, “hello” + “world” etc.
\b: Backspace.
\n: New Line
\t: Tab
\f: Form Feed
\r: Carriage Return
\\: Backslash Character (\)
\’ : Single Quote
\”: Double Quote
4. Array Literals
Array literals are a list of expressions or other constant values, each of which expression
known as an array element. An array literal contains a list of element s within square
brackets ‘ [ ] ‘ . If no value is a pass when it creates an empty array with zero length. If
elements are passed then its length is set to the number of elements passed. Examples for
string are var color = [ ], var fruits = [“Apple”, “Orange”, “Mango”, “Banana”] (an array
of four elements).
5. Boolean Literals
Boolean literals in JavaScript have only two literal values that are true and false.
var userObject = { }
var student = { f-name : “John”, l-name : “D”, “rno” : 23, “marks” : 60}
Javascript operators
JavaScript supports most of the traditional operators, which are grouped depending on
their functionality as follows
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Conditional Operators
x=5+"5";
[Link](x);
x="5"+5;
[Link](x);
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:
Operator Description Example
== is equal to x==8 is false
x==5 is true
=== is exactly equal to (value and type)
x==="5" is false
!= is not equal x!=8 is true
> is greater than x>8 is false
< is less than x<8 is true
>= is greater than or equal to x>=8 is false
<= is less than or equal to x<=8 is true
Logical Operators
Logical operators are used in 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".
Conditional Statements
Very often when you write code, you want to perform different actions for different
decisions. You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
if statement - use this statement if you want to execute some code only if a
specified condition is true
if...else statement - use this statement if you want 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 if you want to select one of many
blocks of code to be executed
switch statement - use this statement if you want to select one of many blocks of
code to be executed
If Statement
You should use the if statement if you want to execute some code only if a specified
condition is true.
Syntax
if (condition)
if (time<10)
{
[Link]("<b>Good morning</b>");
}
</script>
Example 2
<script type="text/javascript">
//Write "Lunch-time!" if the time is 11
var d=new Date();
var time=[Link]();
if (time==11)
{
[Link]("<b>Lunch-time!</b>");
}
</script>
Note: When comparing variables you must always use two equals signs next to each
other (==)!
Notice that there is no ..else.. in this syntax. You just tell the code to execute some code
only if the specified condition is true.
If...else Statement
If you want to execute some code if a condition is true and another code if the condition
is not true, use the if....else statement.
Syntax
if (condition)
[Link] RAO Assistant Professor(SVIT) Page 11
Department of CSE(IOT)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Example
<script type="text/javascript">
//If the time is less than 10,
//you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date();
var time = [Link]();
Control statements
The while loop
The while loop is used when you want the loop to execute and continue executing while
the specified condition is true.
while (condition)
{
code to be executed
}
Note: The <= could be any comparing statement.
Example
Explanation: The example below defines a loop that starts with i=0. The loop will
continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the
[Link] RAO Assistant Professor(SVIT) Page 14
Department of CSE(IOT)
loop runs.
<html>
<body>
<script type="text/javascript">
var i=0;
while (i<=10)
{
[Link]("The number is " + i);
[Link]("<br />");
i=i+1;
}
</script>
</body>
</html>
Result
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10
The do...while Loop
The do...while loop is a variant of the while loop. This loop will always execute a block
of code ONCE, and then it will repeat the loop as long as the specified condition is true.
This loop will always be executed at least once, even if the condition is false, because
the code is executed before the condition is tested.
do
{
code to be executed
}
while (condition);
A for loop will execute a code block for a number of times. Compared to other loops,
FOR is shorter and easy to debug as it contains initialization, condition and update exp..
Syntax:
With initialize, it starts the loop, here a declared variable is used. Then the exit condition
for the loop is checked in condition part. When this condition returns true, the code
block inside is executed. When, in case, if the condition returns false or fails, it goes to
increment/decrement part and the variable is assigned an updated value. Values are
updated until the condition is satisfied.
JavaScript For...In Statement
The for...in statement is used to loop (iterate) through the elements of an array or
through the properties of an object.
The code in the body of the for ... in loop is executed once for each element/property.
JavaScript Functions
Syntax
://defining a function
function <function-name>(parameters)
Parameter passing
function halveIt(a)
{
a=a/2; //a=2;
}
var x=4;
halveIt(x);
[Link](“x=”+x); //x=4;
Program to print factorial of each number upto given number ‘n’( n=6).
<html>
<head>
<script language="javascript">
function fact(n)
{
prod=1;
for(var i=2;i<=n;i++)
prod*=i;
return prod;
}
for(var i=1;i<=6;i++)
[Link](i+"!="+fact(i)+",");
</script>
</head>
</html>
<html>
<head>
<script language ="javascript">
function fib(n)
{
if (n==0 ||n==1) return 1;
else
{
var a=fib(n-1);
var b=fib(n-2);
return a+b;
}
}
[Link](fib(5));
</script>
</head>
</html>
Arrays in JavaScript
JavaScript arrays are different from arrays in other languages. Traditionally, an array is
considered to be a collection of homogeneous items. It means an array cannot contain
dissimilar items. JavaScript’s approach to arrays is a bit different. There isn’t a data type
called array in JavaScript. Instead, arrays are objects in JavaScript. A JavaScript Object
can hold different data types (string, integer, boolean) at once:
An array variable may be created by assigning an array literal to it. An array literal is
written using square brackets with array elements separated by comma(,) as follows
2. The traditional for loop can used to iterate through an array. JavaScript arrays
are objects and provide several useful properties and methods to work with
it. The property length specifies the size of array of the array.
var odds=[1,3,5,7];
var sum=0;
for(i=0;I,[Link];i++)
[Link](sum);
as mentioned a JavaScript array may contain heterogeneous elements. One can
declare an array that contains various information about an employee such as name,
age, marital status and salary. The declaration of such an array will look like this
var employee[“john”,24,false,18000];
3. JavaScript arrays are dynamic in nature. It means that elements can be added
and deleted and when required. For efficient memory usage, an array should
contain those elements that are actually required. Determining array size in
advance during the creation of the array is also a major problem. JavaScript
dynamic arrays eliminate all theses problems.
var primes=[2,3,5,7]; //length 4
primes[4]=11; //length 5 adds an element at the end.
This code segment first creates an array of length4. It then adds an element to the
end of the array which changes array size to [Link] following statement also adds
an element at the end.
1. The first constructor does not take any argument and creates an empty array(i.e.
an array of length zero) elements may be added later as and when needed.
var colors=new Array(); // array of length zero
This code segment creates an array of length zero. Now consider the following
statement
colors[2]=”blue”; //length3
This statement not creates elements colors[2] but also the elements colors[0] and
colors[1]. The length of the array colors then becomes 3. Here the values of
colors[0] and colors[1] are yet undefined. However their values may be assigned
later.
2. Programmer may also specify the initial length of the array during creation as
follows
Colors=new Array(2);
This creates the array colors of initial length [Link] so far no values have been
assigned to the elements colors[0] and colors[1]. So these elements are yet
undefined. Elements may be assigned later as required.
Elements can be added dynamically on demand
Colors[3]=”violet”; //length 4
3. Programmers may also explicitly specify the elements of an array during its
creation. The length of the array will be the number of lelments specified.
var cars=new array[“Maruti”,”Tata”,”Ford”];
the content is accessed by keys, whatever the method used to declare the array.
var y = arr["one"];
2) indexOf()
The indexOf() method in JavaScript is a built-in function used to find the first
occurrence of a specified value within a string or an array. It returns the index
(position) of the first match, or -1 if the value is not found.
[Link] RAO Assistant Professor(SVIT) Page 23
Department of CSE(IOT)
/*Demo program on indexOf()*/
<html>
<head>
<script language="javascript">
fruits = ["Banana", "Orange", "Apple", "Mango"];
index = [Link]("Apple");
[Link]([Link]("Apple"));
</script>
</head>
<body>
</body>
3)join()
The join() method in JavaScript is an Array instance method used to create and
return a new string by concatenating all of the elements in an array.
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The join() Method</h2>
<p>join() returns an array as a string:</p>
<p id="demo"></p>
<script>
fruits = ["Banana", "Orange", "Apple", "Mango"];
text = [Link]();
[Link]("demo").innerHTML = text;
</script>
</body>
</html>
4) pop()
The pop() method in JavaScript is a built-in Array method used to remove the last
element from an array and return that removed element
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The pop() Method</h2>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]();
[Link]("demo").innerHTML = fruits;
</script>
</body>
</html>
5) reverse()
The reverse() method in JavaScript is a built-in Array method that reverses the
order of the elements in an array in place. This means it modifies the original array
directly, without creating a new one.
JavaScript String
The JavaScript string is an object that represents a sequence of characters.
1. By string literal
2. By string object (using new keyword)
[Link] RAO Assistant Professor(SVIT) Page 27
Department of CSE(IOT)
1) By string literal
The string literal is created using double quotes. The syntax of creating string using
string literal is given below:
Example program
<script>
var str="This is string literal";
[Link](str);
</script>
The syntax of creating string object using new keyword is given below:
<script>
var stringname=new String("hello javascript string");
[Link](stringname);
</script>
Methods Description
substring() It is used to fetch the part of the given string on the basis of the
specified index.
toLocaleLowerCase( It converts the given string into lowercase letter on the basis of
) host?s current locale.
split() It splits a string into substring array, then returns that newly
created array.
trim() It trims the white space from the left and right side of the string.
Example
<script>
var str="javascript";
[Link]([Link](2));
</script>
The JavaScript String indexOf(str) method returns the index position of the given string.
The JavaScript String lastIndexOf(str) method returns the last index position of the given
string.
<script>
var s1="javascript from javatpoint indexof";
var n=[Link]("java");
[Link](n);
</script>
The JavaScript String toLowerCase() method returns the given string in lowercase
letters.
The JavaScript String toUpperCase() method returns the given string in uppercase letters.
<script>
var s1="JavaScript toUpperCase Example";
Output:
The JavaScript String 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
Output:
CdCde
The JavaScript String trim() method removes leading and trailing whitespaces from the
string.
Example
<script>
var s1=" javascript trim ";
var s2=[Link]();
[Link](s2);
</script>
Output:
javascript trim
Syntax
[Link](separator, limit)
Parameters
Paramete Description
r
separator Optional.
A string or regular expression to use for splitting.
If omitted, an array with the original string is returned.
limit Optional.
An integer that limits the number of splits.
Items after the limit are excluded.
Example
<script>
var str="This is JavaTpoint website";
[Link]([Link](" ")); //splits the given string.
</script>
4. JavaScript Math
The JavaScript math object provides several constants and methods to perform
mathematical operation. Unlike date object, it doesn't have constructors.
Methods Description
1) abs()
[Link] RAO Assistant Professor(SVIT) Page 38
Department of CSE(IOT)
The abs() method in JavaScript is a static method of the built-in Math object, used to
return the absolute value of a number.
Syntax
[Link](number)
Example
<html>
<body>
<h1>JavaScript Math</h1>
<h2>The [Link]() Method</h2>
<p>[Link]() returns the absolute value of a number:</p>
<p id="demo"></p>
<script>
let a = [Link](7.25);
let b = [Link](-7.25);
let c = [Link](null);
let d = [Link]("Hello");
let e = [Link](2-3);
[Link]("demo").innerHTML =
a + "<br>" + b + "<br>" + c + "<br>" + d + "<br>" + e;
</script>
</body>
</html>
Output
7.25
7.25
0
NaN
1
2) ceil()
[Link] RAO Assistant Professor(SVIT) Page 39
Department of CSE(IOT)
The [Link]() method in JavaScript is a static method of the built-in Math object. It is
used to round a number up to the nearest integer
Syntax
[Link](number)
Example
<html>
<body>
<h1>JavaScript Math</h1>
<h2>The [Link]() Method</h2>
<p>[Link]() rounds a number UP to the nearest integer:</p>
<p id="demo"></p>
<script>
a = [Link](0.60);
b = [Link](0.40);
c = [Link](5);
d = [Link](5.1);
e = [Link](-5.1);
f = [Link](-5.9);
[Link]("demo").innerHTML =
a + "<br>" + b + "<br>" + c + "<br>" + d + "<br>" + e + "<br>" + f;
</script>
</body>
</html>
EXample
1
1
5
6
-5
-5
3) max()
[Link] RAO Assistant Professor(SVIT) Page 40
Department of CSE(IOT)
In JavaScript, the max() method refers to the static method [Link](). This method is
part of the built-in Math object and is used to determine the largest value among a set of
numbers.
Syntax
Example
<html>
<body>
<h1>JavaScript Math</h1>
<h2>The [Link]() Method</h2>
<script>
let a = [Link](5, 10);
let b = [Link](0, 150, 30, 20, 38);
let c = [Link](-5, 10);
let d = [Link](-5, -10);
let e = [Link](1.5, 2.5);
[Link]("demo").innerHTML =
a + "<br>" + b + "<br>" + c + "<br>" + d + "<br>" + e;
</script>
</body>
</html>
4) min()
synatx
[Link](n1, n2,...)
<html>
<body>
<h1>JavaScript Math</h1>
<h2>The [Link]() Method</h2>
output
The [Link]() Method
Return the numbers with the lowest value:
5
0
-5
-10
1.5
The following figure shows the Window object in the hierarchy of Browsers objects.
JavaScript Window Object is an already available global object which represents the
currently opened window tab in the browser. It can be said that the window object is
nothing but the browser window which is opened in the browser. This Window object is
different from the normal object, a window is an object of browser. Every tab opened in
the browser will have its window object associated with it and it will be available in
every part of the application as it is global. It has multiple values and methods are
available with it and we can call these methods directly to perform multiple operations
over the browser window.
All data and information about any browser is attached to the window object as
properties and the frames property in the window object returns all the frames in the
current window.
The table given below describes properties of the window object in JavaScript.
The methods of the window object enable you to perform various tasks such as open a
url in a new window or to close a window. The following table describes the methods of
the Window object in JavaScript.
Method Description
The [Link]() method accepts three arguments: the URL to load, the window
target and a string of window features.
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.
Constructors
we 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)
Methods Description
getDay() It returns the integer value between 0 and 6 that represents the
day of the week on the basis of local time.
getFullYears() It returns the integer value that represents the year on the basis
of local time.
getMilliseconds() It returns the integer value between 0 and 999 that represents
the milliseconds on the basis of local time.
setDate() It sets the day value for the specified date on the basis of local
time.
setDay() It sets the particular day of the week on the basis of local time.
setFullYears() It sets the year value for the specified date on the basis of local
time.
setHours() It sets the hour value for the specified date on the basis of
local time.
setMilliseconds() It sets the millisecond value for the specified date on the basis
of local time.
setMinutes() It sets the minute value for the specified date on the basis of
setMonth() It sets the month value for the specified date on the basis of
local time.
setSeconds() It sets the second value for the specified date on the basis of
local time.
<html>
<head><title>Date object</title>
<script language=javascript>
var d=new Date();
[Link]("<html><body><h1>Date Object methods</h1>");
[Link]("<table border=1 cellspacing=0 cellpadding=0>");
[Link]("<tr>");
[Link]("<td>");
[Link]("Today's date & Time");
[Link]("</td>");
[Link]("<td>");
[Link](d+"</td>");
[Link]("</tr>");
[Link]("<tr>");
[Link]("<td>");
[Link]("Only Date");
[Link]("</td>");
[Link]("<td>");
[Link]([Link]()+"</td>");
[Link]("</tr>");
[Link]("<tr>");
[Link]("<td>");
[Link]("Only Day");
[Link]("</td>");
[Link]("<td>");
[Link]([Link]()+"</td>");
[Link]("</tr>");
[Link]("<tr>");
[Link]("<td>");
[Link]("Only Year");
[Link]("</td>");
[Link]("<td>");
[Link]([Link]()+"</td>");
[Link]("</tr>");
[Link]("<tr>");
[Link]("<td>");
[Link]("Only Time");
[Link]("</td>");
[Link]("<td>");
[Link]([Link]()+"</td>");
[Link]("</tr>");
[Link]("<tr>");
[Link]("<td>");
[Link]("Only Hours");
[Link]("</td>");
[Link]("<td>");
[Link]([Link]()+"</td>");
[Link]("</tr>");
[Link]("<tr>");
[Link]("<td>");
[Link]("Only Minutes");
[Link]("</td>");
[Link]("<tr>");
[Link]("<td>");
[Link]("Only Seconds");
[Link]("</td>");
[Link]("<td>");
[Link]([Link]()+"</td>");
[Link]("</tr>");
[Link]("<tr>");
[Link]("<td>");
[Link]("London Time");
[Link]("</td>");
[Link]("<td>");
[Link]([Link]()+"</td>");
[Link]("</tr>");
[Link]("</html>");
</script>
</head>
<body>
</body>
</html>
The prompt() method in JavaScript is used to display a prompt box that prompts the
user for the input. It is generally used to take the input from the user before entering the
page. It can be written without using the window prefix. When the prompt box pops up,
we have to click "OK" or "Cancel" to proceed.
The box is displayed using the prompt() method, which takes two arguments: The first
argument is the label which displays in the text box, and the second argument is the
default string, which displays in the textbox. The prompt box consists of two
buttons, OK and Cancel. It returns null or the string entered by the user. When the user
clicks "OK," the box returns the input value. Otherwise, it returns null on clicking
"Cancel".
[Link] RAO Assistant Professor(SVIT) Page 52
Department of CSE(IOT)
The prompt box takes the focus and forces the user to read the specified message. So, it
should avoid overusing this method because it stops the user from accessing the other
parts of the webpage until the box is closed.
Syntax
prompt(message, default)
The confirm() method displays a dialog box with a specified message, along with an OK
and a Cancel button.
A confirm box is often used if you want the user to verify or accept something.
Note: The confirm box takes the focus away from the current window, and forces the
browser to read the message. Do not overuse this method, as it prevents the user from
accessing other parts of the page until the box is closed.
The confirm() method returns true if the user clicked "OK", and false otherwise.
Syntax
confirm(message)
javaScript 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
[Link]("sometext");
You can use a JavaScript function named isNaN to validate a number object. Here is an
example shows how to validate numbers using JavaScript:
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE>JavaScript Number Validation</TITLE>
<SCRIPT type="text/javascript">
function validateNumber(this_form2)
{
var num2 = this_form2.[Link];
if(num2==null|| num2=="")
{
alert("Please enter a number.");
this_form2.[Link]();
return false;
}
if(isNaN(num2))
{
alert("It is not a valid number.");
this_form2.[Link]();
return false;
}
return true;
}
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
Here is an example shows how to validate phone number entered by the user using
JavaScript:
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE>JavaScript Phone Number Validation</TITLE>
<SCRIPT type="text/javascript">
function validatePhoneNumber(this_form4)
{
var phon=this_form4.[Link];
if(phon==null||phon=="")
{
alert("Please enter your phone number.");
this_form4.[Link]();
return false;
}
if(isNaN(phon))
{
alert("Sorry! You have entered an invalid phone number! Please try again.");
this_form4.[Link]();
return false;
}
if([Link]<10)
{
alert("Phone number must be at least of 10 digits.");
this_form4.[Link]();
return false;
}
return true;
}
</SCRIPT>
[Link] RAO Assistant Professor(SVIT) Page 55
Department of CSE(IOT)
</HEAD>
<BODY>
</BODY>
</HTML>
<HTML>
<HEAD>
<TITLE>JavaScript Username and Password Validation</TITLE>
<SCRIPT type="text/javascript">
function validateUsernamePassword(this_form3)
{
var userName = this_form3.user_name.value;
var pass1 = this_form3.[Link];
var pass2 = this_form3.[Link];
if(userName=="")
{
alert("Please enter your username.");
this_form3.user_name.focus();
return false;
}
if([Link]<6)
{
alert("Username must be at least of 6 characters.");
this_form3.user_name.focus();
return false;
}
if(pass1=="")
{
alert("Please enter your password.");
this_form3.[Link]();
return false;
}
if([Link]<8)
<BODY>
<FORM action="#" validateUsernamePassword(this)"
method="Post">
Enter Username: <INPUT type="text" name="user_name"/><BR/>
Enter Password: <INPUT type="password" name="password1"/><BR/>
Re-enter Password: <INPUT type="password" name="password2"/><BR/>
<INPUT type="submit" value="Login"/>
</FORM>
</BODY>
</HTML>
For example :submitting an HTML form, moving mouse over a web page, clicking
the mouse button will generate an event informing the browser that an action has
occurred and that further relevant processing is required.
The browser waits for events to occur, and when they do, it performs whatever
processing is assigned to those events. The processing that is performed in response to
the occurrence of an event is known as event handling. The code that performs this
processing is called an event handler.
HTML event handlers can be divided into two types interactive and non–
interactive.
A interactive event handler depends on the user interaction with an HTML page.
For example onClick and onMouseOver event handlers are interactive event handlers.
This required the user to click a button object or move the mouse cursor over a web
page.
Non-interactive event handler does not need user interaction. For example “onLoad”
event handler is a non-interactive event handler as it is executed whenever a web
page is loaded in to the browser.
The handler eventHandler of the event evnt for some element ele is specified by
assigning it to the property of the element. The name of the property for the event evnt
takes the following form onEvnt.
For example, the name of the property for the evnt Click is onClick. Similarly
onMouseOver is the name of the property for the mouseOver.
There are many ways to add a handler to an event. The straightforward way is to
specify it in the tag as follows
</script>
</head>
<body>
<h1> hai</h1>
<form name=f1>
<select ><option value=1>red</option>
<option value=2>green</option>
<option value=3>yellow</option>
</select>
</form>
</body>
</html>
<html>
<head>
<title>mouse coordinates</title>
<script>
function callme()
{
<html>
<head><title>Change event</title>
<script language=javascript>
function callme()
{
var str=[Link];
[Link]=[Link]();
}
</script>
</head>
<body>
<form name=f1>
<table>
<tr>
<td> Enter ant Text</td>
<td><input type=text name=t1 ></tr>
<tr>
<td> converted Text is</td>
<td><input type=text name=t2></td>
</tr>
</table>
</form>
</body>
</html>
<html>
<head><title>validation</title>
<script language=javascript>
function validate()
{
if([Link]==0)
{
alert("Username can never be blank");
return false;
}
if([Link]==0)
{
alert("Password can never be blank");
return false;
}
return true;
}
</script>
</head>
<body>
<form name=f1 validate()">
<table>
<tr>
<td>Username</td>
<td><input type=text name=t1></td>
</tr>
<tr>
<td>password</td>
<td><input type=password name=t2></td>
</tr>
<tr>
<th colspan=2>
<input type=submit value=submit></th>
</tr>
</table>
</form>
</body>
</html>
<html>
<head>
<title>Key Event</title>
<script>
function callme()
{
var str="key pressed: "+ [Link]([Link]);
str=str+ " ,key code :"+[Link];
alert(str);
}
</script>
</head>
<body ></body>
</html>
<html>
<head>
<title>Anchor</title>
<script language="javascript">
function callme(k,b,c)
{
[Link]=b;
[Link]=c;
}
</script>
</head>
<body>
<a href="[Link]" >>
</body>
</html>
1. isNaN()
Syntax
isNaN(value);
Syntax:
parseInt(string, radix);
Parameters:
string: The value to parse. If it's not a string, it will be converted to one.
radix (optional): An integer between 2 and 36 representing the base of
the numeral system to be used. If omitted, it defaults to 10
(decimal). Common radix values include 2 (binary), 8 (octal), 10
(decimal), and 16 (hexadecimal).
Example 1:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML =
parseInt("10") + "<br>" +
parseInt("10.00") + "<br>" +
parseInt("10.33") + "<br>" +
parseInt("34 45 66") + "<br>" +
[Link] RAO Assistant Professor(SVIT) Page 67
Department of CSE(IOT)
parseInt(" 60 ") + "<br>" +
parseInt("40 years") + "<br>" +
parseInt("He was 40");
</script>
</body>
</html>
Example 2:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML =
parseInt("10", 10)+ "<br>" +
parseInt("010")+ "<br>" +
parseInt("10", 8)+ "<br>" +
[Link] RAO Assistant Professor(SVIT) Page 68
Department of CSE(IOT)
parseInt("0x10")+ "<br>" +
parseInt("10", 16);
</script>
</body>
</html>
2. eval()
Example 1
Example 3
// Output
document. writeln(eval(state));
1. The eval function can execute any type of code, including malicious
code that can compromise the security of your system. For example,
attackers may steal sensitive data.
2. The eval function can be slow for large amounts of code.
Example 1:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Global Methods</h1>
<h2>The isFinite() Method</h2>
<p>isFinite() returns false if a value is Infinity, -Infinity, or NaN, otherwise
true:</p>
<p id="demo"></p>
<script>
result =
isFinite(-1.23) + "<br>" +
isFinite(5-2) + "<br>" +
isFinite(0) + "<br>";
[Link]("demo").innerHTML = result;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Global Methods</h1>
<h2>The isFinite() Method</h2>
<p>isFinite() returns false if a value is Infinity, -Infinity, or NaN, otherwise
true:</p>
<p id="demo"></p>
<script>
let result =
isFinite("Hello") + "<br>" +
isFinite("2005/12/12");
[Link]("demo").innerHTML = result;
</script>
</body>
</html>
Syntax
encodeURI(uri)
Example 1:
!DOCTYPE html>
<p id="demo"></p>
<script>
uri = "my [Link]?name=ståle&car=saab";
lencoded = encodeURI(uri);
decoded = decodeURI(encoded);