Lesson Plan No.
1: Algorithm and flow charts
Algorithms:- To make a computer do anything, you have to write a computer
program. To write a computer program, you have to tell the computer, step by
step, exactly what you want it to do. The computer then "executes" the
program, following each step mechanically, to accomplish the end goal.
When you are telling the computer what to do, you also get to choose how it's
going to do it. That's where computer algorithms come in. The algorithm is
the basic technique used to get the job done. Let's follow an example to help
get an understanding of the algorithm concept.
Let's say that you have a friend arriving at the airport, and your friend needs to
get from the airport to your house. Here are four different algorithms that you
might give your friend for getting to your home:
The taxi algorithm:
1. Go to the taxi stand.
2. Get in a taxi.
3. Give the driver my address.
The call-me algorithm:
1. When your plane arrives, call my cell phone.
2. Meet me outside baggage claim.
The rent-a-car algorithm:
1. Take the shuttle to the rental car place.
2. Rent a car.
3. Follow the directions to get to my house.
The bus algorithm:
1.
2.
3.
4.
Outside baggage claim, catch bus number 70.
Transfer to bus 14 on Main Street.
Get off on Elm street.
Walk two blocks north to my house.
All four of these algorithms accomplish exactly the same goal, but each
algorithm does it in completely different way. Each algorithm also has a different
cost and a different travel time. Taking a taxi, for example, is probably the
fastest way, but also the most expensive. Taking the bus is definitely less
expensive, but a whole lot slower. You choose the algorithm based on the
circumstances.
Summary :- The sequence of steps to be performed in order to solve a
problem by the computer is known as an algorithm
Flowchart :- A flowchart is a type of diagram that represents an algorithm,
workflow or process, showing the steps as boxes of various kinds, and their
order by connecting them with arrows. This diagrammatic representation
illustrates a solution model to a given problem.
For Example :-
Summary :- Flowchart is a graphical or symbolic representation of an
algorithm. It is the diagrammatic representation of the step-by-step solution to
a given problem
Lesson Plan No. 2:
their features
Introduction to Web server and
Introduction to Web server :- Web servers are computers that deliver
(serves up) Web pages. Every Web server has an IP address and possibly a
domain
name.
For
example,
if
you
enter
the
URL
http://www.pcwebopedia.com/index.html in your browser, this sends a request
to the Web server whose domain name is pcwebopedia.com.
The server then fetches the page named index.html and sends it to your
browser. Any computer can be turned into a Web server by installing server
software and connecting the machine to the Internet. There are many Web
server software applications, including public domain software from NCSA and
Apache, and commercial packages from Microsoft, Netscape and others.
Most web servers have features that allow you to do the
following:
Create one or more websites.
Configure log file settings, including where the log files are saved, what
data to include on the log files etc.
Configure website/directory security. For example, which user accounts
are/aren't allowed to view the website, which IP addresses are/aren't
allowed to view the website etc.
Create an FTP site. An FTP site allows users to transfer files to and from
the site.
Create virtual directories, and map them to physical directories
Configure/nominate custom error pages. This allows you to build and
display user friendly error messages on your website. For example, you
can specify which page is displayed when a user tries to access a page
that doesn't exist (i.e. a "404 error").
Specify default documents.
Lesson Plan No. 3: Introduction to Programming &
Scripting Languages
Introduction to Programming :- A program is a set of instructions that
tell the computer to do various things; sometimes the instruction it has to
perform depends on what happened when it performed a previous instruction.
This section gives an overview of the two main ways in which you can give
these instructions, or commands as they are usually called. One way uses an
interpreter, the other a compiler. As human languages are too difficult for a
computer to understand in an unambiguous way, commands are usually written
in one or other languages specially designed for the purpose.
Introduction to Scripting language :- A scripting language or script
language is a programming language that supports scripts, programs written for
a special run-time environment that can interpret (rather than compile) and
automate the execution of tasks that could alternatively be executed one-byone by a human operator.
Java script
Java script is a client slide scripting language which is used to change HTML
static page into dynamic pages or it brings interactivity in HTML web pages.
A client side scripting language means , it has support in the browser &
doesnt require a web server to be executed
Java script is supported by all major browsers and it is written inside HTML
document.
The History of Java script
Java script was initially introduced by Netscape a web browser in 1995
.The first author of this language was Brendan Eich.
Java scripts first version was released in 1993 and the latest version is
3.0
Java script has support for communicating with web server and that was
included in Java script in 2000
In 2006 Java script released its most popular library called jQuery which
is now used by millions of websites on the web.
Difference between Client side & server side Scripting
Language
Server side scripting language (PHP,ASP) requires a separate
online server for execution .
While Client side scripting language (Java script, DHTML) doesnt
require a web server.
The source code of a client side (Java script ) is always visible to
the users.
While Server side scripting source code is not available to the
users .
Lesson Plan No.4: Introduction to JavaScript & its
application for web.
JavaScript
JavaScript is an object-based scripting language that is lightweight and crossplatform.
JavaScript is not compiled but translated. The JavaScript Translator (embedded
in browser) is responsible to translate the JavaScript code.
Where JavaScript is used
JavaScript is used to create interactive websites. It is mainly used for:
1) Client-side validation
2) Dynamic drop-down menus
3) Displaying data and time
4) Displaying popup windows and dialog boxes (like alert dialog box, confirm
dialog box and prompt dialog box)
5) Displaying clocks etc.
JavaScript Example
Program 1:
<html>
<body>
<h2>Welcome to JavaScript</h2>
<script> document.write("Hello JavaScript"); </script>
</body>
</html>
Out Put:Welcome to JavaScript
Hello JavaScript
JavaScript Example
1. JavaScript Example
2. Within body tag
3. Within head tag
Javascript example is easy to code. JavaScript provides 3 places to put the
JavaScript code: within body tag, within head tag and external JavaScript file.
Lets create the first JavaScript example.
<script type="text/javascript">
document.write("JavaScript is a simple language for learners");
</script>
The script tag specifies that we are using JavaScript.
The text/javascript is the content type that provides information to the
browser about the data.
The document.write() function is used to display dynamic content through
JavaScript. We will learn about document object in detail later.
Places to put JavaScript code
1. Between the body tag of html
2. Between the head tag of html/li>
3. In .js file (external javaScript)
1) JavaScript Example : code between the body tag
In the above example, we have displayed the dynamic content using JavaScript.
Lets see the simple example of JavaScript that displays alert dialog box.
Program 2:
<html>
<body>
<script>
document.write("Hello JavaScript");
</script>
</body>
</html>
Out Put:Hello JavaScript
2) JavaScript Example : code between the head tag
Lets see the same example of displaying alert dialog box of JavaScript that is
contained inside the head tag.
In this example, we are creating a function msg(). To create function in
JavaScript, you need to write function with function_name as given below.
To call function, you need to work on event. Here we are using onclick event to
call msg() function.
Program 3:
<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello Javatpoint");
}
</script>
</head>
<body>
<p>Welcome to Javascript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
Output:
Welcome to Javascript
3) External JavaScript file
We can create external JavaScript file and embed it in many html page.
It provides code re usability because single JavaScript file can be used in
several html pages.
An external JavaScript file must be saved by .js extension. It is recommended
to embed all JavaScript files into a single file. It increases the speed of the
webpage.
Lets create an external JavaScript file that prints Hello Javatpoint in a alert
dialog box.
message.js
function msg(){
alert("Hello Javatpoint");
}
Program 4:
<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
JavaScript Comment
1. JavaScript comments
2. Advantage of javaScript comments
3. Single-line and Multi-line comments
The JavaScript comments are meaningful way to deliver message. It is used
to add information about the code, warnings or suggestions so that end user
can easily interpret the code.
The JavaScript comment is ignored by the JavaScript engine i.e. embedded in
the browser.
Advantages of JavaScript comments
There are mainly two advantages of JavaScript comments.
1. To make code easy to understand It can be used to elaborate the code
so that end user can easily understand the code.
2. To avoid the unnecessary code It can also be used to avoid the code
being executed. Sometimes, we add the code to perform some action. But
after sometime, there may be need to disable the code. In such case, it is
better to use comments.
Types of JavaScript Comments
There are two types of comments in JavaScript.
1. Single-line Comment
2. Multi-line Comment
JavaScript Single line Comment
It is represented by double forward slashes (//). It can be used before and after
the statement.
Lets see the example of single-line comment i.e. added before the statement.
<script>
// It is single line comment
document.write("hello javascript");
</script>
Lets see the example of single-line comment i.e. added after the statement.
<script>
var a=10;
var b=20;
var c=a+b;//It adds values of a and b variable
document.write(c);//prints sum of 10 and 20
</script>
JavaScript Multi line Comment
It can be used to add single as well as multi line comments. So, it is more
convenient.
It is represented by forward slash with asterisk then asterisk with forward slash.
For example:
/* your code here */
It can be used before, after and middle of the statement.
<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</script>
Lesson Plan No. 5: JavaScript Basics Variables,
Constants & Data types
JavaScript Variable
1. JavaScript variable
2. JavaScript Local variable
3. JavaScript Global variable
A JavaScript variable is simply a name of storage location. There are two
types of variables in JavaScript : local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as
identifiers).
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or
dollar( $ ) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different
variables.
Correct JavaScript variables
var x = 10;
var _value="sonoo";
Incorrect JavaScript variables
var 123=30;
var *aa=320;
Lets see a simple example of JavaScript variable.
Program 5:
<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>
Output of the above example: 30
JavaScript local variable
A JavaScript local variable is declared inside block or function. It is accessible
within the function or block only. For example:
<script>
function abc(){
var x=10;//local variable
}
</script>
Or,
<script>
If(10<13){
var y=20;//JavaScript local variable
}
</script>
JavaScript global variable
A JavaScript global variable is accessible from any function. A variable i.e.
declared outside the function or declared with window object is known as global
variable. For example:
Program 6:
<html>
<body>
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>
</body>
</html>
OutPut:
200 200
JavaScript Global Variable
A JavaScript global variable is declared outside the function or declared with
window object. It can be accessed from any function.
Lets see the simple example of global variable in JavaScript.
Program 7:
<html>
<body>
<script>
var value=50;//global variable
function a(){
alert(value);
}
function b(){
alert(value);
}
a();
</script>
</body>
</html>
OutPut: 50
Declaring JavaScript global variable within function
To declare JavaScript global variables inside function, you need to use window
object. For example:
window.value=90;
Now it can be declared inside any function and can be accessed from any
function. For example:
function m(){
window.value=100;//declaring global variable by window object
}
function n(){
alert(window.value);//accessing global variable from other function
}
Program 8:
<html>
<body>
<script>
function m(){
window.value=100;//declaring global variable by window object
}
function n(){
alert(window.value);//accessing global variable from other function
}
m();
n();
</script>
</body>
</html>
O/P: 100
Internals of global variable in JavaScript
When you declare a variable outside the function, it is added in the window
object internally. You can access it through window object also. For example:
var value=50;
function a(){
alert(window.value);//accessing global variable
}
Javascript Data Types
JavaScript provides different data types to hold different types of values. 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. For example:
var a=40;//holding number
var b="Rahul";//holding string
JavaScript primitive data types
There are five types of primitive data types in JavaScript. They are as follows:
Data Type
Description
String
represents sequence of characters e.g. "hello"
Number
represents numeric values e.g. 100
Boolean
represents boolean value either false or true
Undefined
represents undefined value
Null
represents null i.e. no value at all
JavaScript non-primitive data types
The non-primitive data types are as follows:
Data Type
Description
Object
represents instance through which we can access members
Array
represents group of similar values
RegExp
represents regular expression
Lesson Plan No. 6: JavaScript Operators
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on
operands. For example:
var sum=10+20;
Here, + is the arithmetic operator and = is the assignment operator.
There are following types of operators in JavaScript.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on the
operands. The following operators are known as JavaScript arithmetic
operators.
Operator
+
Description
Addition
Example
10+20 = 30
Subtraction
20-10 = 10
Multiplication
10*20 = 200
Division
20/10 = 2
Modulus (Remainder)
20%10 = 0
++
Increment
var a=10; a++; Now a = 11
--
Decrement
var a=10; a--; Now a = 9
JavaScript Comparison Operators
The JavaScript comparison operator compares the two operands. The
comparison operators are as follows:
Operator
Description
Example
==
Is equal to
10==20 = false
===
Identical (equal and of same type)
10==20 = false
!=
Not equal to
10!=20 = true
!==
Not Identical
20!==20 = false
>
Greater than
20>10 = true
>=
Greater than or equal to
20>=10 = true
<
Less than
20<10 = false
<=
Less than or equal to
20<=10 = false
JavaScript Bitwise Operators
The bitwise operators perform bitwise operations on operands. The bitwise
operators are as follows:
Operator
Description
Example
&
Bitwise AND
(10==20 & 20==33) = false
Bitwise OR
(10==20 | 20==33) = false
Bitwise XOR
(10==20 ^ 20==33) = false
Bitwise NOT
(~10) = -10
<<
Bitwise Left Shift
(10<<2) = 40
>>
Bitwise Right Shift
(10>>2) = 2
>>>
Bitwise Right Shift with
Zero
(10>>>2) = 2
JavaScript Logical Operators
The following operators are known as JavaScript logical operators.
Operator
Description
Example
&&
Logical AND
(10==20 && 20==33) = false
||
Logical OR
(10==20 || 20==33) = false
Logical Not
!(10==20) = true
JavaScript Assignment Operators
The following operators are known as JavaScript assignment operators.
Operator Description
Example
Assign
10+10 = 20
+=
Add and assign
var a=10; a+=20; Now a = 30
-=
Subtract and assign
var a=20; a+=10; Now a = 10
*=
Multiply and assign
var a=10; a*=20; Now a = 200
/=
Divide and assign
var a=10; a/=2; Now a = 5
%=
Modulus and assign
var a=10; a%=2; Now a = 0
JavaScript Special Operators
The following operators are known as JavaScript special operators.
Operator
Description
(?:)
Conditional Operator returns value based on the condition. It is like
if-else.
Comma Operator allows multiple expressions to be evaluated as
single statement.
delete
Delete Operator deletes a property from the object.
in
In Operator checks if object has the given property
instanceof checks if the object is an instance of given type
new
creates an instance (object)
typeof
checks the type of object.
void
it discards the expression's return value.
yield
checks what is returned in a generator by the generator's iterator.
Operator Precedence:
Precedence
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Operators
Parentheses , array subscripts or function call
!, ~, -, ++, -*, /, %
+,<<, >>, >>>
<, <=, >, >=
==, !=
&
^
|
&&
||
?:
=, +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, ^=, |=
The operator determines which operations are evaluated before others during the parsing and
execution of complex expressions
The precedence of the operator which operations are evaluated before others during the parsing
and execution of complex expressions.
Lesson Plan No. 7: Program Control Statements and
loops.
Program Control Statement
JavaScript If-else
The JavaScript if-else statement is used to execute the code whether
condition is true or false. There are three forms of if statement in JavaScript.
1. If Statement
2. If else statement
3. if else if statement
JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if
statement is given below.
if(expression){
//content to be evaluated
}
Flowchart of JavaScript If statement
Lets see the simple example of if statement in javascript.
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
Output of the above example
value of a is greater than 10
Program:
<html>
<body>
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
</body>
</html>
O/P: value of a is greater than 10
JavaScript If...else Statement
It evaluates the content whether condition is true of false. The syntax of
JavaScript if-else statement is given below.
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
Flowchart of JavaScript If...else statement
Lets see the example of if-else statement in JavaScript to find out the even or
odd number.
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
Output of the above example
a is even number
Program:
<html>
<body>
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
</body>
</html>
OutPut: a is even number
JavaScript If...else if statement
It evaluates the content only if expression is true from several expressions. The
signature of JavaScript if else if statement is given below.
if(expression1){
//content to be evaluated
}
else if(expression2){
//content to be evaluated
}
else if(expression3){
//content to be evaluated
}
else{
//content to be evaluated
}
if expression1 is true
if expression2 is true
if expression3 is true
if no expression is true
Lets see the simple example of if else if statement in javascript.
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
Output of the above example
a is equal to 20
Program:
<html>
<body>
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
</body>
</html>
Output of the above example
a is equal to 20
JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple
expressions. It is just like else if statement that we have learned in previous
page. But it is convenient than if..else..if because it can be used with numbers,
characters etc.
The signature of JavaScript switch statement is given below.
switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......
default:
code to be executed if above values are not matched;
}
Program:
<!DOCTYPE html>
<html>
<body>
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
Output of the above example
B Grade
Program:
<!DOCTYPE html>
<html>
<body>
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result+=" A Grade";
case 'B':
result+=" B Grade";
case 'C':
result+=" C Grade";
default:
result+=" No Grade";
}
document.write(result);
</script>
</body>
Output of the above example
B Grade B Grade C Grade No Grade
JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do
while or for-in loops. It makes the code compact. It is mostly used in array.
There are four types of loops in JavaScript.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
1) JavaScript 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. The syntax of for loop is given
below.
for (initialization; condition; increment)
{
code to be executed
}
Lets see the simple example of for loop in javascript.
Program:
<!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
</body>
</html>
Output:
1
2
3
4
5
2) JavaScript while loop
The JavaScript while loop iterates the elements for the infinite number of
times. It should be used if number of iteration is not known. The syntax of while
loop is given below.
while (condition)
{
code to be executed
}
Lets see the simple example of while loop in javascript.
Program:
<!DOCTYPE html>
<html>
<body>
<script>
var i=11;
while (i<=13)
{
document.write(i + "<br/>");
i++;
}
</script>
</body>
</html>
Output:
11
12
13
3) JavaScript do while loop
The JavaScript do while loop iterates the elements for the infinite number of
times like while loop. But, code is executed at least once whether condition is
true or false. The syntax of do while loop is given below.
do{
code to be executed
}while (condition);
Lets see the simple example of do while loop in javascript.
Program:
<!DOCTYPE html>
<html>
<body>
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=23);
</script>
</body>
</html>
Output:
21
22
23
Lesson Plan No. 8: Arrays in JavaScript concepts,
types & usage.
JavaScript Array
JavaScript array is an object that represents a collection of similar type of
elements.
There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
1) JavaScript array literal
The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
Lets see the simple example of creating and using array in JavaScript.
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
Program:
<html>
<body>
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
</body>
</html>
Output of the above example
Sonoo
Vimal
Ratan
2) JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:
var arrayname=new Array();
Here, new keyword is used to create instance of array.
Lets see the example of creating array directly.
Program:
<html>
<body>
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>
Output of the above example
Arun
Varun
John
JavaScript array constructor (new keyword)
Here, you need to create instance of array by passing arguments in constructor
so that we don't have to provide value explicitely.
The example of creating object by array constructor is given below.
Program:
<html>
<body>
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>
Output of the above example
Jai
Vijay
Smith
Lesson Plan No. 9: Introduction to Functions in
JavaScript
JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript
function many times to reuse the code.
Advantage of JavaScript function
There are mainly two advantages of JavaScript functions.
1. Code reusability: We can call a function several times so it save coding.
2. Less coding: It makes our program compact. We dont need to write
many lines of code each time to perform a common task.
JavaScript Function Syntax
The syntax of declaring function is given below.
function functionName([arg1, arg2, ...argN]){
//code to be executed
}
JavaScript Functions can have 0 or more arguments.
JavaScript Function Example
Lets see the simple example of function in JavaScript that does not has
arguments.
Program:
<html>
<body>
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
</body>
</html>
Output:
Function Arguments
We can call function by passing arguments. Lets see the example of function
that has one argument.
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
Program:
<html>
<body>
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
</body>
</html>
Function with Return Value
We can call function that returns a value and use it in our program. Lets see
the example of function that returns value.
Program:
<html>
<body>
<script>
function getInfo(){
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
</body>
</html>
Output of the above example
hello javatpoint! How r u?
Lesson Plan No. 10: Built in JavaScript functions
overview.
JavaScript Objects
A JavaScript object is an entity having state and behavior (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.
Creating Objects in JavaScript
There are 3 ways to create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
1) JavaScript Object 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).
Lets see the simple example of creating object in JavaScript.
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
Program:
<html>
<body>
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body> </html>
Output of the above example: 102 Shyam Kumar 40000
2) By creating instance of Object
The syntax of creating object directly is given below:
var objectname=new Object();
Here, new keyword is used to create object.
Lets see the example of creating object directly.
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
Program:
<html>
<body>
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>
Output of the above example
101 Ravi 50000
3) By using an Object constructor
Here, you need to create function with arguments. Each argument value can be
assigned in the current object by using this keyword.
The this keyword refers to the current object.
The example of creating object by object constructor is given below.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
Program:
<html>
<body>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
</body>
</html>
Output of the above example
103 Vimal Jaiswal 30000
Defining method in JavaScript Object
We can define method in JavaScript object. But before defining method, we
need to add property in the function with same name as method.
The example of defining method in object is given below.
Program:
<html>
<body>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
}
}
e=new emp(103,"Sonoo Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
</script>
</body>
</html>
Output of the above example
103 Sonoo Jaiswal 30000
103 Sonoo Jaiswal 45000
Lesson Plan No. 11: The String data type in
JavaScript.
Introduction to String, Math and Date Functions.
JavaScript String
The JavaScript string is an object that represents a sequence of characters.
There are 2 ways to create string in JavaScript
1. By string literal
2. By string object (using new keyword)
1) By string literal
The string literal is created using double quotes. The syntax of creating string
using string literal is given below:
var stringname="string value";
Lets see the simple example of creating string literal.
Program:
<!DOCTYPE html>
<html> <body>
<script>
var str="This is string literal";
document.write(str);
</script>
</body></html>
Output: This is string literal
2) By string object (using new keyword)
The syntax of creating string object using new keyword is given below:
var stringname=new String("string literal");
Here, new keyword is used to create instance of string.
Lets see the example of creating string in JavaScript by new keyword.
<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>
Program:
<!DOCTYPE html>
<html>
<body>
<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>
</body>
</html>
Output:
hello javascript string
JavaScript String Methods
Let's see the list of JavaScript string methods with examples.
1) charAt(index)
2) concat(str)
3) indexOf(str)
4) lastIndexOf(str)
5) toLowerCase()
6) toUpperCase()
7) slice(beginIndex, endIndex)
8) trim()
1) JavaScript String charAt(index) Method
The JavaScript String charAt() method returns the character at the given index.
<script>
var str="javascript";
document.write(str.charAt(2));
</script>
Program:
<!DOCTYPE html>
<html>
<body>
<script>
var str="javascript";
document.write(str.charAt(2));
</script>
</body>
</html>
Output: v
2) JavaScript String concat(str) Method
The JavaScript String concat(str) method concatenates or joins two strings.
<script>
var s1="javascript ";
var s2="concat example";
var s3=s1.concat(s2);
document.write(s3);
</script>
Program:
<!DOCTYPE html>
<html> <body> <script>
var s1="javascript ";
var s2="concat example";
var s3=s1+s2;
document.write(s3);
</script> </body> </html>
Output:
javascript concat example
3) JavaScript String indexOf(str) Method
The JavaScript String indexOf(str) method returns the index position of the
given string.
<script>
var s1="javascript from javatpoint indexof";
var n=s1.indexOf("from");
document.write(n);
</script>
Program:
<!DOCTYPE html>
<html>
<body>
<script>
var s1="javascript from javatpoint indexof";
var n=s1.indexOf("from");
document.write(n);
</script>
</body>
</html>]
Output: 11
4) JavaScript String lastIndexOf(str) Method
The JavaScript String lastIndexOf(str) method returns the last index position of
the given string.
<script>
var s1="javascript from javatpoint indexof";
var n=s1.lastIndexOf("java");
document.write(n);
</script>
Output: 16
5) JavaScript String toLowerCase() Method
The JavaScript String toLowerCase() method returns the given string in
lowercase letters.
<script>
var s1="JavaScript toLowerCase Example";
var s2=s1.toLowerCase();
document.write(s2);
</script>
Output:
javascript tolowercase example
6) JavaScript String toUpperCase() Method
The JavaScript String toUpperCase() method returns the given string in
uppercase letters.
<script>
var s1="JavaScript toUpperCase Example";
var s2=s1.toUpperCase();
document.write(s2);
</script>
Output: JAVASCRIPT TOUPPERCASE EXAMPLE
7) JavaScript String slice(beginIndex, endIndex) Method
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.
<script>
var s1="abcdefgh";
var s2=s1.slice(2,5);
document.write(s2);
</script>
Output: cde
8) JavaScript String trim() Method
The JavaScript String trim() method removes leading and trailing whitespaces
from the string.
<script>
var s1="
javascript trim
var s2=s1.trim();
document.write(s2);
</script>
";
Output:
javascript trim
JavaScript 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.
Constructor
1.
2.
3.
4.
You can use 4 variant of Date constructor to create date object.
Date()
Date(milliseconds)
Date(dateString)
Date(year, month, day, hours, minutes, seconds, milliseconds)
JavaScript Date Methods
The important methods of date object are as follows:
Method
Description
getFullYear()
returns the year in 4 digit e.g. 2015. It is a new method and
suggested than getYear() which is now deprecated.
getMonth()
returns the month in 2 digit from 1 to 31.
getDate()
returns the date in 1 or 2 digit from 1 to 31.
getDay()
returns the day of week in 1 digit from 0 to 6.
getHours()
returns all the elements having the given name value.
getMinutes()
returns all the elements having the given class name.
getSeconds()
returns all the elements having the given class name.
getMilliseconds()
returns all the elements having the given tag name.
JavaScript Date Example
Let's see the simple example to print date object. It prints date and time both.
Current Date and Time: <span id="txt"></span>
<script>
var today=new Date();
document.getElementById('txt').innerHTML=today;
</script>
Program:
<html> <body>
Current Date and Time: <span id="txt"></span>
<script>
var today=new Date();
document.getElementById('txt').innerHTML=today;
</script> </body> </html>
OP: Current Date and Time: Thu Apr 09 2015 11:07:18 GMT+0530 (India Standard Time)
JavaScript Current Time Example
Let's see the simple example to print current time of system.
Current Time: <span id="txt"></span>
<script>
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
</script>
Program:
<html> <body>
Current Date and Time: <span id="txt"></span>
<script>
var today=new Date();
document.getElementById('txt').innerHTML=today;
</script> </body> </html>
Output: Current Time: 11:6:41
JavaScript Digital Clock Example
Let's see the simple example to display digital clock using JavaScript date
object.
There are two ways to set interval in JavaScript: by setTimeout() or
setInterval() method.
Program:
<html> <body>
Current Time: <span id="txt"></span>
<script>
window.onload=function(){getTime();}
function getTime(){
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds(); // add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
setTimeout(function(){getTime()},1000);
} //setInterval("getTime()",1000);//another way
function checkTime(i){
if (i<10){
i="0" + i;
}
return i;
} </script> </body> </html>
OP: Current Time
JavaScript Math Object
The JavaScript math object provides several constants and methods to
perform mathematical operation. Unlike date object, it doesn't have
constructors.
Math.sqrt(n)
The JavaScript math.sqrt(n) method returns the square root of the given
number.
Square Root of 17 is: <span id="p1"></span>
<script>
document.getElementById('p1').innerHTML=Math.sqrt(17);
</script>
Program:
<!DOCTYPE html>
<html>
<body>
Square Root of 17 is: <span id="p1"></span>
<script>
document.getElementById('p1').innerHTML=Math.sqrt(17);
</script>
</body>
</html>
Output:
Square Root of 17 is: 4.123105625617661
Math.random()
The JavaScript math.random() method returns the random number between 0
to 1.
Random Number is: <span id="p2"></span>
<script>
document.getElementById('p2').innerHTML=Math.random();
</script>
Output:
Random Number is: 0.8758344054222107
Math.pow(m,n)
The JavaScript math.pow(m,n) method returns the m to the power of n that is
mn.
3 to the power of 4 is: <span id="p3"></span>
<script>
document.getElementById('p3').innerHTML=Math.pow(3,4);
</script>
Output:
3 to the power of 4 is: 81
Math.floor(n)
The JavaScript math.floor(n) method returns the lowest integer for the given
number. For example 3 for 3.7, 5 for 5.9 etc.
Floor of 4.6 is: <span id="p4"></span>
<script>
document.getElementById('p4').innerHTML=Math.floor(4.6);
</script>
Output: Floor of 4.6 is: 4
Math.ceil(n)
The JavaScript math.ceil(n) method returns the largest integer for the given
number. For example 4 for 3.7, 6 for 5.9 etc.
Ceil of 4.6 is: <span id="p5"></span>
<script>
document.getElementById('p5').innerHTML=Math.ceil(4.6);
</script>
Output: Ceil of 4.6 is: 5
Math.round(n)
The JavaScript math.round(n) method returns the rounded integer nearest for
the given number. If fractional part is equal or greater than 0.5, it goes to upper
value 1 otherwise lower value 0.
For example 4 for 3.7, 3 for 3.3, 6 for 5.9 etc.
Round of 4.3 is: <span id="p6"></span><br>
Round of 4.7 is: <span id="p7"></span>
<script>
document.getElementById('p6').innerHTML=Math.round(4.3);
document.getElementById('p7').innerHTML=Math.round(4.7);
</script>
Output:
Round of 4.3 is: 4
Round of 4.7 is: 5
Math.abs(n)
The JavaScript math.abs(n) method returns the absolute value for the given
number. For example 4 for -4, 6.6 for -6.6 etc.
Absolute value of -4 is: <span id="p8"></span>
<script>
document.getElementById('p8').innerHTML=Math.abs(-4);
</script>
Output:
Absolute value of -4 is: 4
Lesson Plan No. 12:- Concepts of Pop Up boxes in
JavaScript
Browser Object Model
1. Browser Object Model (BOM)
The Browser Object Model (BOM) is used to interact with the browser.
The default object of browser is window means you can call all the functions of
window by specifying window or directly. For example:
window.alert("hello javatpoint");
is same as:
alert("hello javatpoint");
You can use a lot of properties (other objects) defined underneath the window
object like document, history, screen, navigator, location, innerHeight,
innerWidth,
Note: The document object represents an html document. It forms DOM (Document
Object Model).
Window Object
1. Window Object
2. Properties of Window Object
3. Methods of Window Object
4. Example of Window Object
The window object represents a window in browser. An object of window is
created automatically by the browser.
Window is the object of browser, it is not the object of javascript. The
javascript objects are string, array, date etc.
Note: if html document contains frame or iframe, browser creates additional window
objects for each frame.
Methods of window object
The important methods of window object are as follows:
Method
Description
alert()
displays the alert box containing message with ok button.
confirm()
displays the confirm dialog box containing message with ok and cancel
button.
prompt()
displays a dialog box to get input from the user.
open()
opens the new window.
close()
closes the current window.
setTimeout() performs action after specified time like calling function, evaluating
expressions etc.
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
window.alert("sometext");
The window.alert method can be written without the window prefix.
Example
alert("I am an alert box!");
OUTPUT :- Click the button to display an alert box:
Try it
Example of alert() in javascript
It displays alert dialog box. It has message and ok button.
<script type="text/javascript">
function msg(){
alert("Hello Alert Box");
}
</script>
<input type="button" value="click" onclick="msg()"/>
Output of the above example
Confirm 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
window.confirm("sometext");
The window.confirm() method can be written without the window prefix.
Example
var r = confirm("Press a button");
if (r == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
OUTPUT:- Click the button to display a confirm box.
Try it
Example of confirm() in javascript
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");
}
else{
alert("cancel");
}
}
</script>
<input type="button" value="delete record" onclick="msg()"/>
Output of the above example
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
window.prompt("sometext","defaultText");
The window.prompt() method can be written without the window prefix.
Example
var person = prompt("Please enter your name", "Harry Potter");
if (person != null) {
document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";
}
Example of prompt() in javascript
It displays prompt dialog box for input. It has message and textfield.
<script type="text/javascript">
function msg(){
var v= prompt("Who are you?");
alert("I am "+v);
}
</script>
<input type="button" value="click" onclick="msg()"/>
Output of the above example
Example of open() in javascript
It displays the content in a new window.
<script type="text/javascript">
function msg(){
open("http://www.javatpoint.com");
}
</script>
<input type="button" value="javatpoint" onclick="msg()"/>
Output of the above example
Example of setTimeout() in javascript
It performs its task after the given milliseconds.
<script type="text/javascript">
function msg(){
setTimeout(
function(){
alert("Welcome to Javatpoint after 2 seconds")
},2000);
}
</script>
<input type="button" value="click" onclick="msg()"/>
Output of the above example
Lesson Plan No. 13:- Introduction to the Document
Object Model.
Document Object Model
1. Document Object
2. Properties of document object
3. Methods of document object
4. Example of document object
1) Document object represents the whole html document.
When html document is loaded in the browser, it becomes a document object. It
is the root element that represents the html document.
As mentioned earlier, it is the object of window. So
window.document
Is same as
document
According to W3C - "The W3C Document Object Model (DOM) is a platform and
language-neutral interface that allows programs and scripts to dynamically
access and update the content, structure, and style of a document."
2) Properties of document object
Let's see the properties of document object that can be accessed and modified
by the document
object.
3) Methods of document object
We can access and change the contents of document by its methods.
The important methods of document object are as follows:
Method
Description
write("string")
writes the given string on the doucment.
writeln("string")
writes the given string on the doucment with
newline character at the end.
getElementById()
returns the element having the given id value.
getElementsByName()
returns all the elements having the given name
value.
getElementsByTagName()
returns all the elements having the given tag name.
getElementsByClassName()
returns all the elements having the given class
name.
Accessing the field value by document object
In this example, we are going to get the value of input text by user. Here, we
are usingdocument.form1.name.value to get the value of name field.
Here, document is the root element that represents the html document.
form1 is the name of the form.
name is the attribute name of the input text.
value is the property, that returns the value of the input text.
Let's see the simple example of document object that prints name with
welcome message.
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
Output of the above example
Enter Name:
Javascript - document.getElementById() method
1. getElementById() method
2. Example of getElementById()
The document.getElementById() method returns the element of specified id.
In the previous page, we have used document.form1.name.valueto get the
value of the input value. Instead of this, we can use
document.getElementById() method to get value of the input text. But we need
to define id for the input field.
Let's see the simple example of document.getElementById() method that prints
cube of the given number.
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
Output of the above example
Enter No:
Javascript - document.getElementsByName() method
1. getElementsByName() method
2. Example of getElementsByName()
The document.getElementsByName() method returns all the element of
specified name.
The syntax of the getElementsByName() method is given below:
document.getElementsByName("name")
Here, name is required.
Example of document.getElementsByName() method
In this example, we going to count total number of genders. Here, we are using
getElementsByName() method to get all the genders.
<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">
<input type="button" onclick="totalelements()" value="Total Genders">
</form>
Output of the above example
Male:
Female:
Javascript - document.getElementsByTagName() method
1. getElementsByTagName() method
2. Example of getElementsByTagName()
The document.getElementsByTagName() method returns all the element of
specified tag name.
The syntax of the getElementsByTagName() method is given below:
document.getElementsByTagName("name")
Here, name is required.
Example of document.getElementsByTagName() method
In this example, we going to count total number of paragraphs used in the
document. To do this, we have called the
document.getElementsByTagName("p") method that returns the total
paragraphs.
<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length);
}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by getElemen
tByTagName() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>
Output of the above example
This is a pragraph
Here we are going to count total number of paragraphs by
getElementByTagName() method.
Let's see the simple example
count paragraph
Another example of document.getElementsByTagName() method
In this example, we going to count total number of h2 and h3 tags used in the
document.
<script type="text/javascript">
function counth2(){
var totalh2=document.getElementsByTagName("h2");
alert("total h2 tags are: "+totalh2.length);
}
function counth3(){
var totalh3=document.getElementsByTagName("h3");
alert("total h3 tags are: "+totalh3.length);
}
</script>
<h2>This is h2 tag</h2>
<h2>This is h2 tag</h2>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<button onclick="counth2()">count h2</button>
<button onclick="counth3()">count h3</button>
Output of the above example
This is h2 tag
This is h2 tag
This is h3 tag
This is h3 tag
This is h3 tag
count h2 count h3
Note: Output of the given examples may differ on this page because it will count the
total number of para , total number of h2 and total number of h3 tags used in
this document.
Javascript - innerHTML
1. javascript innerHTML
2. Example of innerHTML property
The innerHTML property can be used to write the dynamic html on the html
document.
It is used mostly in the web pages to generate the dynamic html such as
registration form, comment form, links etc.
Example of innerHTML property
In this example, we are going to create the html form when user clicks on the
button.
In this example, we are dynamically writing the html form inside the div name
having the id mylocation. We are identifing this position by calling the
document.getElementById() method.
<script type="text/javascript" >
function showcommentform() {
var data="Name:<input type='text' name='name'><br>Comment:<texta
rea rows='5' cols='80'></textarea><br><input type='submit' value='co
mment'>";
document.getElementById('mylocation').innerHTML=data;
}
</script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()"
>
<div id="mylocation"></div>
</form>
Output of the above example
Next TopicJavascript innerText
Javascript - innerText
1. javascript innerText
2. Example of innerText property
The innerText property can be used to write the dynamic text on the html
document. Here, text will not be interpreted as html text but a normal text.
It is used mostly in the web pages to generate the dynamic content such as
writing the validation message, password strength etc.
Example of innerText property
In this example, we are going to display the password strength when releases
the key after press.
<script type="text/javascript" >
function validate() {
var msg;
if(document.myForm.userPass.value.length>5){
msg="good";
}
else{
msg="poor";
}
document.getElementById('mylocation').innerText=msg;
}
</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()
">
Strength:<span id="mylocation">no strength</span>
</form>
Output of the above example
Strength:no strength
JavaScript Form Validation
1. JavaScript form validation
2. Example of JavaScript validation
3. JavaScript email validation
It is important to validate the form submitted by the user because it can have
inappropriate values. So validation is must.
The JavaScript provides you the facility the validate the form on the client side
so processing will be fast than server-side validation. So, most of the web
developers prefer JavaScript form validation.
Through JavaScript, we can validate name, password, email, date, mobile
number etc fields.
JavaScript form validation example
In this example, we are going to validate the name and password. The name
cant be empty and password cant be less than 6 characters long.
Here, we are validating the form on form submit. The user will not be forwarded
to the next page until given values are correct.
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="abc.jsp" onsubmit="retu
rn validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
JavaScript Retype Password Validation
<script type="text/javascript">
function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;
if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>
<form name="f1" action="register.jsp" onsubmit="return matchpass()">
Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password" nam
e="password2"/><br/>
<input type="submit">
</form>
JavaScript Number Validation
Let's validate the textfield for numeric value only. Here, we are using isNaN()
function.
<script>
function validate(){
var num=document.myform.num.value;
if (isNaN(num)){
document.getElementById("numloc").innerHTML="Enter Numeric value
only";
return false;
}else{
return true;
}
}
</script>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></spa
n><br/>
<input type="submit" value="submit">
</form>
JavaScript validation with image
Lets see an interactive JavaScript form validation example that displays correct
and incorrect image if input is correct or incorrect.
<script>
function validate(){
var name=document.f1.name.value;
var password=document.f1.password.value;
var status=false;
if(name.length<1){
document.getElementById("nameloc").innerHTML=
"<img src='unchecked.gif'/> Please enter your name";
status=false;
}else{
document.getElementById("nameloc").innerHTML="<img src='checked.gi
f'/>";
status=true;
}
if(password.length<6){
document.getElementById("passwordloc").innerHTML=
"<img src='unchecked.gif'/> Password must be at least 6 char long";
status=false;
}else{
document.getElementById("passwordloc").innerHTML="<img src='checke
d.gif'/>";
status=true;
}
return status;
}
</script>
<form name="f1" action="#" onsubmit="return validate()">
<table>
<tr><td>Enter Name:</td><td><input type="text" name="name"/
>
<span id="nameloc"></span></td></tr>
<tr><td>Enter Password:</td><td><input type="text" name="pass
word"/>
<span id="passwordloc"></span></td></tr>
<tr><td colspan="2"><input type="submit" value="register"/></td>
</tr>
</table>
</form>
Output:
Enter Name:
Enter Password:
Submit
JavaScript email validation
We can validate the email by the help of JavaScript.
There are many criteria that need to be follow to validate the email id such as:
email id must contain the @ and . character
There must be at least one character before and after the @.
There must be at least two characters after . (dot).
Let's see the simple example to validate the email field.
<html>
<body>
<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n
dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post"
action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return
validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
HTML/DOM events for JavaScript
HTML or DOM events are widely used in JavaScript code. JavaScript code is
executed with HTML/DOM events. So before learning JavaScript, lets have
some idea about events.
Events
Description
onclick
occurs when element is clicked.
ondblclick
occurs when element is double-clicked.
onfocus
occurs when an element gets focus such as button, input,
textarea etc.
onblur
occurs when form looses the focus from an element.
onsubmit
occurs when form is submitted.
onmouseover
occurs when mouse is moved over an element.
onmouseout
occurs when mouse is moved out from an element (after
moved over).
onmousedown
occurs when mouse button is pressed over an element.
onmouseup
occurs when mouse is released from an element (after
mouse is pressed).
onload
occurs when document, object or frameset is loaded.
onunload
occurs when body or frameset is unloaded.
onscroll
occurs when document is scrolled.
onresized
occurs when document is resized.
onreset
occurs when form is reset.
onkeydown
occurs when key is being pressed.
onkeypress
occurs when user presses the key.
onkeyup
occurs when key is released.