Javascript-Unit-3
Javascript-Unit-3
<html> <body>
<script language = "javascript" type =
"text/javascript">
<!-- document.write("Hello World!") //-->
</script>
<noscript> Sorry...JavaScript is needed to go
ahead. </noscript>
</body>
</html>
JavaScript - Placement in HTML File
There is a flexibility given to include JavaScript
code anywhere in an HTML document. However the
most preferred ways to include JavaScript in an
HTML file are as follows −
Script in <head>...</head> section.
Script in <body>...</body> section.
Script in <body>...</body> and
<head>...</head> sections.
Script in an external file and then include in
<head>...</head> section.
JavaScript in <head>...</head> section
<html> <head>
<script type = "text/javascript">
<!-- function sayHello() { alert("Hello World") } //-->
</script>
</head> <body>
<input type = "button" onclick = "sayHello()" value =
"Say Hello" />
</body>
</html>
JavaScript in <body>...</body> section
<html> <head>
<script type = "text/javascript">
<!-- function sayHello() {
alert("Hello World") } //--> </script>
</head> <body>
<script type = "text/javascript">
<!-- document.write("Hello World") //-->
</script>
<input type = "button" onclick = "sayHello()" value = "Say
Hello" />
</body> </html>
JavaScript in External File
<html> <head>
<script type = "text/javascript" src = "filename.js" >
</script>
</head>
<body> ....... </body>
</html>
JavaScript Datatypes
One of the most fundamental characteristics of a
programming language is the set of data types it
supports.
These are the type of values that can be represented
and manipulated in a programming language.
JavaScript allows you to work with three primitive data
types −
Numbers, eg. 123, 120.50 etc.
Strings of text e.g. "This text string" etc.
Boolean e.g. true or false.
JavaScript also defines two trivial data
types, null and undefined, each of which defines only
a single value. In addition to these primitive data types,
JavaScript supports a composite data type known
as object. We will cover objects in detail in a separate
chapter.
Note − JavaScript does not make a distinction between
integer values and floating-point values. All numbers in
JavaScript are represented as floating-point values.
JavaScript represents numbers using the 64-bit floating-
point format defined by the IEEE 754 standard.
JavaScript - Variables
Like many other programming languages,
JavaScript has variables. Variables can be thought
of as named containers. You can place data into
these containers and then refer to the data simply
by naming the container.
Before you use a variable in a JavaScript program,
you must declare it. Variables are declared with
the var keyword as follows.
<script type = "text/javascript">
<!–
var money; var name;
Storing a value in a variable is called
//--> variable initialization.
</script> You can do variable initialization at the time of
variable creation or at a later point in time when
you need that variable.
4 / (Division)
Divide the numerator by the denominator
Ex: B / A will give 2
5 % (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0
6 ++ (Increment)
Increases an integer value by one
Ex: A++ will give 11
7 -- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9
<html>
<body> document.write("a + b + c = ");
<script type = "text/javascript"> result = a + b + c;
<!– document.write(result);
var a = 33; document.write(linebreak);
var b = 10; a = ++a;
var c = "Test"; document.write("++a = ");
var linebreak = "<br />"; result = ++a;
document.write("a + b = "); document.write(result);
result = a + b; document.write(result); document.write(linebreak);
document.write(linebreak); b = --b;
document.write("a - b = "); document.write("--b = ");
result = a - b; result = --b;
document.write(result); document.write(result);
document.write(linebreak); document.write(linebreak);
document.write("a / b = "); //-->
result = a / b; </script>
document.write(result); Set the variables to different values and then try...
document.write(linebreak); </body>
document.write("a % b = "); </html>
result = a % b; document.write(result);
document.write(linebreak);
Comparison Operators
JavaScript supports the following comparison
operators −
Assume variable A holds 10 and variable B holds
20, then −
Sr.No. Operator & Description
1 = = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition
becomes true.
Ex: (A == B) is not true.
2 != (Not Equal)
Checks if the value of two operands are equal or not, if the values are not
equal, then the condition becomes true.
Ex: (A != B) is true.
3 > (Greater than)
Checks if the value of the left operand is greater than the value of the right
operand, if yes, then the condition becomes true.
Ex: (A > B) is not true.
4 < (Less than)
Checks if the value of the left operand is less than the value of the right
operand, if yes, then the condition becomes true.
Ex: (A < B) is true.
5 >= (Greater than or Equal to)
Checks if the value of the left operand is greater than or equal to the value
of the right operand, if yes, then the condition becomes true.
Ex: (A >= B) is not true.
6 <= (Less than or Equal to)
Checks if the value of the left operand is less than or equal to the value of
the right operand, if yes, then the condition becomes true.
Ex: (A <= B) is true.
<html>
<body> document.write(result);
<script type = "text/javascript"> document.write(linebreak);
<!– document.write("(a >= b) => ");
var a = 10; result = (a >= b);
var b = 20; document.write(result);
var linebreak = "<br />"; document.write(linebreak);
document.write("(a == b) => "); document.write("(a <= b) => ");
result = (a == b); result = (a <= b);
document.write(result); document.write(result);
document.write(linebreak); document.write(linebreak);
document.write("(a < b) => "); //-->
result = (a < b); </script>
document.write(result); Set the variables to different values and different
document.write(linebreak); operators and then try...
document.write("(a > b) => "); </body>
result = (a > b); </html>
document.write(result);
document.write(linebreak);
document.write("(a != b) => ");
result = (a != b);
Logical Operators
JavaScript supports the following logical operators −
Assume variable A holds 10 and variable B holds 20,
then −
Sr.No. Operator & Description
1 && (Logical AND)
If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.
2 || (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
3 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical
NOT operator will make it false.
Ex: ! (A && B) is false.
<html>
<body>
<script type = "text/javascript">
<!–
var a = true;
var b = false;
var linebreak = "<br />";
document.write("(a && b) => ");
result = (a && b);
document.write(result);
document.write(linebreak);
document.write("(a || b) => ");
result = (a || b);
document.write(result);
document.write(linebreak);
document.write("!(a && b) => ");
result = (!(a && b));
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body> </html>
Bitwise Operators
JavaScript supports the following bitwise operators
Assume variable A holds 2 and variable B holds 3, then
Sr.No. Operator & Description
1 & (Bitwise AND)
It performs a Boolean AND operation on each bit of its integer arguments.
Ex: (A & B) is 2.
2 | (BitWise OR)
It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.
3 ^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its integer
arguments. Exclusive OR means that either operand one is true or operand two
is true, but not both.
Ex: (A ^ B) is 1.
4 ~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand.
Ex: (~B) is -4.
5 << (Left Shift)
It moves all the bits in its first operand to the left by the number of places
specified in the second operand. New bits are filled with zeros. Shifting a value
left by one position is equivalent to multiplying it by 2, shifting two positions is
equivalent to multiplying by 4, and so on.
Ex: (A << 1) is 4.
6 >> (Right Shift)
Binary Right Shift Operator. The left operand’s value is moved right by the
number of bits specified by the right operand.
Ex: (A >> 1) is 1.
7 >>> (Right shift with Zero)
This operator is just like the >> operator, except that the bits shifted in on the
left are always zero.
Ex: (A >>> 1) is 1.
<html>
document.write(linebreak);
<body>
document.write("(a << b) => ");
<script type = "text/javascript">
result = (a << b);
<!–
document.write(result);
var a = 2; // Bit presentation 10
document.write(linebreak);
var b = 3; // Bit presentation 11
document.write("(a >> b) => ");
var linebreak = "<br />";
result = (a >> b);
document.write("(a & b) => ");
document.write(result);
result = (a & b);
document.write(linebreak);
document.write(result);
//-->
document.write(linebreak);
</script>
document.write("(a | b) => ");
<p>Set the variables to different values and
result = (a | b);
different operators and then try...</p>
document.write(result);
</body>
document.write(linebreak);
</html>
document.write("(a ^ b) => ");
result = (a ^ b);
document.write(result);
document.write(linebreak);
document.write("(~b) => ");
result = (~b);
document.write(result);
Assignment Operators
Sr.No. Operator & Description
1 = (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C
do {
Statement(s) to be executed;
} while (expression);
<html>
<body>
<script type = "text/javascript">
<!–
var count = 0;
document.write("Starting Loop" + "<br />");
do {
document.write("Current Count : " + count + "<br />");
count++;
} while (count < 5);
document.write ("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
For loop
The 'for' loop is the most compact form of looping. It
includes the following three important parts −
The loop initialization where we initialize our counter
to a starting value. The initialization statement is
executed before the loop begins.
The test statement which will test if a given condition is
true or not. If the condition is true, then the code given
inside the loop will be executed, otherwise the control
will come out of the loop.
The iteration statement where you can increase or
decrease your counter.
Syntax
for (initialization; test condition; iteration statement)
{
Statement(s) to be executed if test condition is true
}
<html>
<body>
<script type = "text/javascript">
<!–
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++) {
document.write("Current Count : " + count )
; document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
For in loop
The for...in loop is used to loop through an object's
properties.
As we have not discussed Objects yet, you may not feel
comfortable with this loop. But once you understand how
objects behave in JavaScript, you will find this loop
very useful.
Syntax
for (variablename in object) {
statement or block to execute
}
In each iteration, one property from object is
assigned to variablename and this loop continues
till all the properties of the object are exhausted.
Example
Try the following example to implement ‘for-in’ loop.
It prints the web browser’s Navigator object.
<html>
<body>
<script type = "text/javascript">
<!–
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator) {
document.write(aProperty);
document.write("<br />");
}
document.write ("Exiting from the loop!");
//-->
</script>
<p>Set the variable to different object and then try...</p>
</body>
</html>
Loop Control
JavaScript provides full control to handle loops and
switch statements. There may be a situation when you
need to come out of a loop without reaching its bottom.
There may also be a situation when you want to skip a
part of your code block and start the next iteration of
the loop.
To handle all such situations, JavaScript
provides break and continue statements. These
statements are used to immediately come out of any
loop or to start the next iteration of any loop
respectively.
The break Statement
The break statement, which was briefly introduced
with the switch statement, is used to exit a loop
early, breaking out of the enclosing curly braces.
<html>
<body>
<script type = "text/javascript">
<!–
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20) {
if (x == 5) {
break; // breaks out of loop completely }
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
The continue Statement
The continue statement tells the interpreter to
immediately start the next iteration of the loop and
skip the remaining code block. When
a continuestatement is encountered, the program
flow moves to the loop check expression
immediately and if the condition remains true, then
it starts the next iteration, otherwise the control
comes out of the loop.
Example
<html>
<body>
<script type = "text/javascript">
<!–
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 10) {
x = x + 1;
if (x == 5) {
continue; // skip rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Using Labels to Control the Flow
Starting from JavaScript 1.2, a label can be used
with break and continue to control the flow more
precisely. A label is simply an identifier followed by a
colon (:) that is applied to a statement or a block of
code. We will see two different examples to
understand how to use labels with break and continue.
Note − Line breaks are not allowed between
the ‘continue’ or ‘break’statement and its label name.
Also, there should not be any other statement in
between a label name and associated loop.
<html>
<body>
<script type = "text/javascript">
<!–
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 5; i++) {
document.write("Outerloop: " + i + "<br />");
innerloop:
for (var j = 0; j < 5; j++) {
if (j > 3 ) break ; // Quit the innermost loop
if (i == 2) break innerloop; // Do the same thing
if (i == 4) break outerloop; // Quit the outer loop
document.write("Innerloop: " + j + " <br />");
}
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
</body>
</html>
Array
The Array object lets you store multiple values in a
single variable.
It stores a fixed-size sequential collection of elements of
the same type.
An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of
variables of the same type.
Syntax
Use the following syntax to create an Array object −
var fruits = new Array( "apple", "orange", "mango" );
The Array parameter is a list of strings or integers.
When you specify a single numeric parameter with
the Array constructor, you specify the initial length
of the array. The maximum length allowed for an
array is 4,294,967,295.
You can create array by simply assigning values as
follows −
var fruits = [ "apple", "orange", "mango" ];
var points = new Array(40, 100, 1, 5, 25, 10);
var points = [40, 100, 1, 5, 25, 10];
Array Properties
Sr. No. Property & Description
1 constructorReturns a reference to the array function that created
the object.
2 index
The property represents the zero-based index of the match in the
string
3 input
This property is only present in arrays created by regular
expression matches.
4 lengthReflects the number of elements in an array.
5 prototypeThe prototype property allows you to add properties and
methods to an object.
Function
A function is a group of reusable code which can be called
anywhere in your program.
This eliminates the need of writing the same code again and
again.
It helps programmers in writing modular codes. Functions
allow a programmer to divide a big program into a number
of small and manageable functions.
Like any other advanced programming language, JavaScript
also supports all the features necessary to write modular
code using functions.
JavaScript allows us to write our own functions as well. This
section explains how to write your own functions in
JavaScript.
Function Definition
Before we use a function, we need to define it.
The most common way to define a function in
JavaScript is by using the function keyword,
followed by a unique function name, a list of
parameters (that might be empty), and a statement
block surrounded by curly braces.
Syntax
<script type = "text/javascript">
<!–
function functionname(parameter-list) {
statements
}
//-->
</script>
Example
<script type = "text/javascript">
<!- -
function sayHello() {
alert("Hello there");
}
//-->
</script>
Calling a Function
<html>
<head>
<script type = "text/javascript">
function sayHello() {
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>
Function Parameters
Till now, we have seen functions without parameters.
But there is a facility to pass different parameters
while calling a function. These passed parameters
can be captured inside the function and any
manipulation can be done over those parameters. A
function can take multiple parameters separated by
comma.
<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello(‘Sulove', 39)" value = "Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
The return Statement
A JavaScript function can have an
optional return statement. This is required if you
want to return a value from a function. This
statement should be the last statement in a function.
For example, you can pass two numbers in a
function and then you can expect the function to
return their multiplication in your calling program.
<html>
<head>
<script type = "text/javascript">
function concatenate(first, last) {
var full; full = first + last; return full;
}
function secondFunction() {
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "secondFunction()" value = "Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
Event
JavaScript's interaction with HTML is handled through events
that occur when the user or the browser manipulates a page.
When the page loads, it is called an event. When the user
clicks a button, that click too is an event. Other examples
include events like pressing any key, closing a window,
resizing a window, etc.
Developers can use these events to execute JavaScript
coded responses, which cause buttons to close windows,
messages to be displayed to users, data to be validated,
and virtually any other type of response imaginable.
Events are a part of the Document Object Model (DOM)
Level 3 and every HTML element contains a set of events
which can trigger JavaScript Code.
onclick Event Type
This is the most frequently used event type which
occurs when a user clicks the left button of his
mouse. You can put your validation, warning etc.,
against this event type.
<html>
<head>
<script type = "text/javascript">
<!–
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>
onsubmit Event Type
onsubmit is an event that occurs when you try to
submit a form. You can put your form validation
against this event type.
Example
The following example shows how to use onsubmit.
Here we are calling a validate() function before
submitting a form data to the webserver.
If validate() function returns true, the form will be
submitted, otherwise it will not submit the data.
<html>
<head>
<script type = "text/javascript">
<!–
function validation() {
all validation goes here ......... return either true or false
}
//-->
</script>
</head>
<body>
<form method = "POST" action = "t.cgi" onsubmit = "return validate()">
....... <input type = "submit" value = "Submit" />
</form>
</body>
</html>
onmouseover and onmouseout
These two event types will help you create nice
effects with images or even with text as well.
The onmouseover event triggers when you bring
your mouse over any element and
the onmouseout triggers when you move your
mouse out from that element. Try the following
example.
<html>
<head>
<script type = "text/javascript">
<!–
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover = "over()" onmouseout = "out()">
<h2> This is inside the division </h2>
</div>
</body> https://www.tutorialspoint.com/javascript/javascript_events.htm
</html>
JavaScript is an Object Oriented Programming
(OOP) language. A programming language can be
called object-oriented if it provides four basic
capabilities to developers −
Encapsulation − the capability to store related
information, whether data or methods, together in
an object.
Aggregation − the capability to store one object
inside another object.
Inheritance − the capability of a class to rely upon
another class (or number of classes) for some of its
properties and methods.
Polymorphism − the capability to write one
function or method that works in a variety of
different ways.
Object Properties
Object properties can be any of the three primitive
data types, or any of the abstract data types, such
as another object. Object properties are usually
variables that are used internally in the object's
methods, but can also be globally visible variables
that are used throughout the page.
The syntax for adding a property to an object is −
objectName.objectProperty = propertyValue;
var str = document.title;
Object Methods
Methods are the functions that let the object do something or let
something be done to it. There is a small difference between a
function and a method – at a function is a standalone unit of
statements and a method is attached to an object and can be
referenced by the this keyword.
Methods are useful for everything from displaying the contents of
the object to the screen to performing complex mathematical
operations on a group of local properties and parameters.
For example − Following is a simple example to show how to use
the write() method of document object to write any content on the
document.
document.write("This is test");
User-Defined Objects
All user-defined objects and built-in objects are
descendants of an object called Object.
The new Operator
The new operator is used to create an instance of
an object. To create an object, the new operator is
followed by the constructor method.
In the following example, the constructor methods
are Object(), Array(), and Date(). These constructors
are built-in JavaScript functions.
var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");
The Object() Constructor
A constructor is a function that creates and initializes
an object. JavaScript provides a special constructor
function called Object() to build the object. The
return value of the Object() constructor is assigned
to a variable.
The variable contains a reference to the new object.
The properties assigned to the object are not
variables and are not defined with
the var keyword.
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
var book = new Object(); // Create the object
book.subject = "Perl"; // Assign properties to the object
book.author = "Mohtashim";
</script>
</head>
<body>
<script type = "text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
function book(title, author) {
this.title = title;
this.author = author;
}
</script>
</head>
<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
</script>
</body>
</html>
Defining Methods for an Object
The previous examples demonstrate how the
constructor creates the object and assigns
properties. But we need to complete the definition
of an object by assigning methods to it.
<html>
<head>
<title>User-defined objects</title> </script>
<script type = "text/javascript"> </body>
// Define a function which will work as a method function </html>
addPrice(amount) {
this.price = amount;
}
function book(title, author) {
this.title = title;
this.author = author;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
The 'with' Keyword
The ‘with’ keyword is used as a kind of shorthand
for referencing an object's properties or methods.
The object specified as an argument
to with becomes the default object for the duration
of the block that follows. The properties and
methods for the object can be used without naming
the object.
Syntax
The syntax for with object is as follows −
with (object) {
properties used without the object name and dot
}
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
// Define a function which will work as a method function
addPrice(amount) {
with(this) { myBook.addPrice(100);
price = amount; document.write("Book title is : " + myBook.title + "<br>");
} document.write("Book author is : " + myBook.author + "<br>");
} document.write("Book price is : " + myBook.price + "<br>");
function book(title, author) { </script>
this.title = title; </body>
this.author = author; </html>
this.price = 0;
this.addPrice = addPrice;
// Assign that method as property.
}
</script>
</head>
<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
Getting data from Form and form
validation
Form validation normally used to occur at the server,
after the client had entered all the necessary data and
then pressed the Submit button. If the data entered by
a client was incorrect or was simply missing, the server
would have to send all the data back to the client and
request that the form be resubmitted with correct
information. This was really a lengthy process which
used to put a lot of burden on the server.
JavaScript provides a way to validate form's data on
the client's computer before sending it to the web
server.
Form validation generally performs
two functions.
Basic Validation − First of all, the form must be
checked to make sure all the mandatory fields are
filled in. It would require just a loop through each
field in the form and check for data.
Data Format Validation − Secondly, the data that
is entered must be checked for correct form and
value. Your code must include appropriate logic to
test correctness of data.
<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
<!–
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action = "/cgi-bin/test.cgi" name = "myForm" onsubmit = "return(validate());">
<table cellspacing = "2" cellpadding = "2" border = "1">
<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>
<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>
<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>
<tr>
<td align = "right">Country</td>
<td> <select name = "Country">
<option value = "-1" selected>[choose yours] </option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
Basic Form Validation
First let us see how to do a basic form validation. In
the above form, we are calling validate() to
validate data when onsubmit event is occurring.
The following code shows the implementation of this
validate() function.
<script type = "text/javascript">
<!-- // Form validation code will come here.
function validate() {
if( document.myForm.Name.value == "" ) {
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
} if( document.myForm.EMail.value == "" ) {
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
} if( document.myForm.Zip.value == "" || isNaN( document.myForm.Zip.value )
|| document.myForm.Zip.value.length != 5 ) {
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ; return false;
} if( document.myForm.Country.value == "-1" ) {
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>
Data Format Validation
Now we will see how we can validate our entered
form data before submitting it to the web server.
The following example shows how to validate an
entered email address. An email address must
contain at least a ‘@’ sign and a dot (.). Also, the
‘@’ must not be the first character of the email
address, and the last dot must at least be one
character after the ‘@’ sign.
Example
Try the following code for email validation.
<script type = "text/javascript">
<!–
function validateEmail() {
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 )) {
alert("Please enter correct email ID") document.myForm.EMail.focus() ;
return false;
}
return( true );
}
//-->
</script>
Concept of JQUERY
jQuery is a lightweight, "write less, do more",
JavaScript library.
The purpose of jQuery is to make it much easier to
use JavaScript on your website.
jQuery takes a lot of common tasks that require
many lines of JavaScript code to accomplish, and
wraps them into methods that you can call with a
single line of code.
jQuery library features:
HTML/DOM manipulation
CSS manipulation
HTML event methods
Effects and animations
AJAX
Utilities
<head>
<script src="jquery-3.4.0.min.js"></script>
</head>
jQuery CDN
f you don't want to download and host jQuery
yourself, you can include it from a CDN (Content
Delivery Network).
Both Google and Microsoft host jQuery.
To use jQuery from Google or Microsoft, use one of
the following:
Google CDN:
<head>
<script src="https://ajax.googleapis.com/ajax/libs
/jquery/3.4.0/jquery.min.js"></script>
</head>
Microsoft CDN:
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQu
ery/jquery-3.4.0.min.js">
</script>
</head>
Go through below reference link for more
knowledge
Reference
https://javascript.info/
https://www.tutorialspoint.com/javascript/javascrip
t_enabling.htm
https://www.w3schools.com/jquery/default.asp