0% found this document useful (0 votes)
25 views156 pages

Mod - 2 (1) - Read-Only

Uploaded by

rohithlokesh2912
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views156 pages

Mod - 2 (1) - Read-Only

Uploaded by

rohithlokesh2912
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 156

Course objective

• Understand different kind of Internet


Technologies.
• Learn java-specific web services architecture
• understand the SQL and JDBC
• Learn the AJAX and JSON.
MODULE 2
Client side Programming:
• An Introduction to java Script,
• JavaScript DOM Model,
• Date and Object,
• Regular Expression,
• Exception Handling,
• Validation,
• Built-in Objects,
• Event Handling,
• DHTML with JavaScript,
• JSON introduction, Syntax,
• Function Files,
• Http Request,
• SQL.
JAVASCRIPT
OVERVIEW OF JAVASCRIPT
• ORIGINS
• JavaScript, which was developed by Netscape, was
originally named Mocha but soon was renamed
LiveScript.
• In late 1995 LiveScript became a joint venture of
Netscape and Sun Microsystems, and its name again
was changed, this time to JavaScript.
• A language standard for JavaScript was developed in
the late 1990s by the European Computer
Manufacturers Association (ECMA) as ECMA-262.
• The official name of the standard language is
ECMAScript.
• JavaScript can be divided into three parts: the
core, client side, and server side.
• The core is the heart of the language, including its
operators, expressions, statements, and
subprograms.
• Client-side JavaScript is a collection of objects
that support the control of a browser and
interactions with users.
• Server-side JavaScript is a collection of objects
that make the language useful on a Web server.
JAVASCRIPT AND JAVA
JAVA JAVASCRIPT

Java is programming language JavaScript is a scripting language

It is strongly typed language It is dynamically typed language

Types are known at compile time Compile time type checking is impossible

Objects in java are static JavaScript objects are dynamic

Collection of data members and methods is The number of data members and methods of
fixed at compile time an object can change during execution
USES OF JAVASCRIPT
• The JavaScript was initially introduced to provide
programming capability at both the server and client ends of
web connection
JavaScript therefore is implemented at 2 ends:
1. Client end
2. Server end
• The client side JavaScript is embedded in XHTML
documents and is interpreted by the browser
• It also provides some means of computation, which serves
as an alternative for some tasks done at the server side
• Interactions with users through form elements, such as
buttons and menus, can be conveniently described in
JavaScript. Because button clicks and mouse movements
are easily detected with JavaScript, they can be used to
trigger computations and provide feedback to the user.
• For example, when a user moves the mouse cursor from a
text box, JavaScript can detect that movement and check the
appropriateness of the text box’s value (which presumably
was just filled by the user).
• Even without forms, user interactions are both possible and
simple to program in JavaScript.
• These interactions, which take place in dialog windows,
include getting input from the user and allowing the user to
make choices through buttons.
• It is also easy to generate new content in the browser
display dynamically.
• This transfer of task ensures that the server is not
overloaded and performs only required task
• But client side JavaScript cannot replace serves side
JavaScript; because server side software supports file
operations, database access, security, networking etc
• JavaScript is also used as an alternative to java applets.
• Programming in JavaScript is much simpler than
compared to java
• JavaScript support DOM [Document Object Model]
which enables JavaScript to access and modify CSS
properties and content of any element of a displayed
XHTML document
Document Object Model

• The 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. It
has properties and methods. By the help of
document object, we can add dynamic content
to our web page.
• 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."
Properties of document object
• 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 field value by document object
• In this example, we are going to get the value of input
text by user. Here, we are
using document.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.
<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>
• javascript - document.getElementById() method
• getElementById() method
• Example of getElementById()
• The document.getElementById() method returns
the element of specified id.
• In the previous page, we have
used document.form1.name.value to 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.
<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="numbe
r"/><br/>
<input type="button" value="cube" onclick="getcube()"/
>
</form>
• Javascript - document.getElementsByName()
method
• getElementsByName() method
• 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.
<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>
• Javascript - document.getElementsByTagName()
method
• getElementsByTagName() method
• Example of getElementsByTagName()
• The document.getElementsByTagName() metho
d returns all the element of specified tag name.
• The syntax of the getElementsByTagName()
method is given below:
• document.getElementsByTagName("name")
• Here, name is required.
<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 paragraph
s by getElementByTagName() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button
>
• Javascript - innerHTML
• javascript innerHTML
• 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.
<script type="text/javascript" >
function showcommentform() {
var data="Name:<input type='text' name='name'><br>Comment:<br>
<textarea rows='5' cols='80'></textarea>
<br><input type='submit' value='Comment'>";
document.getElementById('mylocation').innerHTML=data;
}
</script>
<form name="myForm">
<input type="button" value="comment“onclick="showcommentform()
">
<div id="mylocation"></div>
</form>
• Javascript - innerText
• javascript innerText
• 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.
<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>
• 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:va
lueN}
• As you can see, property and value is separated by : (colon).
• Let’s 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>
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.
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp
.salary);
</script>
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.
<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>
• 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.
<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>
S.N
o
JavaScript Object
Methods Description Methods

1 Object.assign() This method is used to copy enumerable and


own properties from a source object to a
target object
2 Object.create() This method is used to create a new object
with the specified prototype object and
properties.
3 Object.defineProperty() This method is used to describe some
behavioral attributes of the property.
4 Object.defineProperties() This method is used to create or configure
multiple object properties.
5 Object.entries() This method returns an array with arrays of
the key, value pairs.
6 Object.freeze() This method prevents existing properties from
being removed.
7 Object.getOwnPropertyDescript This method returns a property descriptor for
or() the specified property of the specified object.
8 Object.getOwnPropertyDescriptors This method returns all own property
() descriptors of a given object.
9 Object.getOwnPropertyNames() This method returns an array of all properties
(enumerable or not) found.
10 Object.getOwnPropertySymbols() This method returns an array of all own
symbol key properties.
11 Object.getPrototypeOf() This method returns the prototype of the
specified object.
12 Object.is() This method determines whether two values
are the same value.
13 Object.isExtensible() This method determines if an object is
extensible
14 Object.isFrozen() This method determines if an object was
frozen.
15 Object.isSealed() This method determines if an object is
sealed.
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
• 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)
Methods JavaScript
Description Date Methods
getDate() It returns the integer value between 1 and 31 that represents the
day for the specified date on the basis of local time.
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.
getHours() It returns the integer value between 0 and 23 that represents the
hours 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.
getMinutes() It returns the integer value between 0 and 59 that represents the
minutes on the basis of local time.
getMonth() It returns the integer value between 0 and 11 that represents the
month on the basis of local time.
JavaScript Date Example

• Current Date and Time: <span id="txt"></spa


n>
• <script>
• var today=new Date();
• document.getElementById('txt').innerHTML=t
oday;
• </script>
JavaScript Date Example

<script>
var date=new Date();
var day=date.getDate();
var month=date.getMonth()+1;
var year=date.getFullYear();
document.write("<br>Date is: "+day+"/"+month
+"/"+year);
</script>
JavaScript Current Time Example

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>
JavaScript Digital Clock Example
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>
Regular Expression

• In JavaScript, a Regular Expression (RegEx) is


an object that describes a sequence of
characters used for defining a search pattern.
For example,
• /^a...s$/
• The above code defines a RegEx pattern. The
pattern is: any five letter string starting
with a and ending with s.
Expression String

abs

alias
/^a...s$/
abyss

Alias
Create a RegEx

• There are two ways you can create a regular


expression in JavaScript.
• Using a regular expression literal:
The regular expression consists of a pattern
enclosed between slashes /.
For example,
• cost regularExp = /abc/;
• Here, /abc/ is a regular expression.
• Using the RegExp() constructor function:
You can also create a regular expression by
calling the RegExp() constructor function. For
example,
• const reguarExp = new RegExp('abc');
• For example,
• const regex = new RegExp(/^a...s$/);
• console.log(regex.test('alias')); // true
• In the above example, the string alias matches
with the RegEx pattern /^a...s$/. Here,
the test() method is used to check if the string
matches the pattern.
• There are several other methods available to
use with JavaScript RegEx.
• If you already know the basics of RegEx, jump
to JavaScript RegEx Methods.
Specify Pattern Using RegEx
• To specify regular expressions, metacharacters are used. In
the above example (/^a...s$/), ^ and $ are metacharacters.
MetaCharacters
• Metacharacters are characters that are interpreted in a
special way by a RegEx engine. Here's a list of
metacharacters:
• [] . ^ $ * + ? {} () \ |
[] - Square brackets
• Square brackets specify a set of characters you wish to
match
Expression String

ac
[abc]
Hey Jude

abc de ca
• Here, [abc] will match if the string you are trying to
match contains any of the a, b or c.
• You can also specify a range of characters using - inside
square brackets.
• [a-e] is the same as [abcde].
• [1-4] is the same as [1234].
• [0-39] is the same as [01239].
• You can complement (invert) the character set by using
caret ^ symbol at the start of a square-bracket.
• [^abc] means any character except a or b or c.
• [^0-9] means any non-digit character.
• . - Period
• A period matches any single character (except
newline '\n').
Expression String Matched?

a No match

ac 1 match

.. acd 1 match

2 matches
acde (contains 4
characters)
• ^ - Caret
• The caret symbol ^ is used to check if a
string starts with a certain character.
Expression String Matched?

a 1 match

^a abc 1 match

bac No match

abc 1 match

^ab No match (starts


acb with a but not
followed by b)
• $ - Dollar
• The dollar symbol $ is used to check if a
string ends with a certain character.

Expression String

a$ formula

cab
• * - Star
• The star symbol * matches zero or more
occurrences of the pattern left to it
Expression String Matched?

mn 1 match

man 1 match

mann 1 match
ma*n
No match (a is not
main
followed by n)

woman 1 match
• + - Plus
• The plus symbol + matches one or more
occurrences of the pattern left to it
Expression String Matched?

No match (no a
mn
character)

man 1 match

ma+n mann 1 match

No match (a is not
main
followed by n)

woman 1 match
• ? - Question Mark
• The question mark symbol ? matches zero or
one occurrence of the pattern left to it.
Expression String

mn

man

ma?n maan

main

woman
• {} - Braces
• Consider this code: {n,m}. This means at
least n, and at most m repetitions of the
pattern left to it.
Expression String

abc dat

abc daat
a{2,3}
aabc daaat

aabc daaaat
• Let's try one more example. This RegEx [0-
9]{2, 4} matches at least 2 digits but not more
than 4 digits.

Expression String

ab123csde

[0-9]{2,4} 12 and 345673

1 and 2
• | - Alternation
• Vertical bar | is used for alternation
(or operator).
Here, a|b match any string that contains either a or b

Expression String Matched?

cde No match

1 match (match
ade
a|b at ade)

3 matches (at
acdbea
acdbea)
• () - Group
• Parentheses () is used to group sub-patterns.
For example, (a|b|c)xz match any string that
matches either a or b or c followed by xz
Expression String

ab xz

(a|b|c)xz abxz

axz cabxz
• \ - Backslash
• Backslash \ is used to escape various characters
including all metacharacters.
For example,
• \$a match if a string contains $ followed by a.
Here, $ is not interpreted by a RegEx engine in a
special way.
• If you are unsure if a character has special
meaning or not, you can put \ in front of it. This
makes sure the character is not treated in a
special way.
• Special Sequences
• Special sequences make commonly used
patterns easier to write. Here's a list of special
sequences:
• \A - Matches if the specified characters are at
the start of a string.
Expression String

the sun
\Athe
In the sun
• \b - Matches if the specified characters are at
the beginning or end of a wordExpression
Expression String

football
\bfoo
a football

a football

the foo
foo\b
the afoo test

the afootest
• \B - Opposite of \b. Matches if the specified
characters are not at the beginning or end of a
word.
Expression String

football
\Bfoo
a football

a football

the foo
foo\B
the afoo test

the afootest
• \d - Matches any decimal digit. Equivalent
to [0-9]
Expression String

12abc3
\d
JavaScript
• \D - Matches any non-decimal digit.
Equivalent to [^0-9]
Expression String

1ab34"50
\D
1345
• \s - Matches where a string contains any
whitespace character. Equivalent to [
\t\n\r\f\v].

Expression String
JavaScript
\s RegEx
JavaScriptRegEx
• \S - Matches where a string contains any non-
whitespace character. Equivalent to [^
\t\n\r\f\v].

Expression String
\S a b
• \w - Matches any alphanumeric character
(digits and alphabets). Equivalent to [a-zA-Z0-
9_]. By the way, underscore _ is also
considered an alphanumeric character.

Expression String

12&": ;c
\w
%"> !
• \W - Matches any non-alphanumeric
character. Equivalent to [^a-zA-Z0-9_]
Expression String
1a2%c
\W
JavaScript
• \Z - Matches if the specified characters are at
the end of a string.
Expression String

I like JavaScript

I like JavaScript
JavaScript\Z
Programming

JavaScript is fun
Exception Handling in JavaScript

• An exception signifies the presence of an


abnormal condition which requires special
operable techniques.
• In programming terms, an exception is the
anomalous code that breaks the normal flow of
the code.
• Such exceptions require specialized
programming constructs for its execution.
What is Exception Handling

• In programming, exception handling is a process or


method used for handling the abnormal statements in
the code and executing them. It also enables to handle
the flow control of the code/program.
• For handling the code, various handlers are used that
process the exception and execute the code.
For example, the Division of a non-zero value with zero
will result into infinity always, and it is an exception.
Thus, with the help of exception handling, it can be
executed and handled.
• In exception handling:
• A throw statement is used to raise an exception. It
means when an abnormal condition occurs, an
exception is thrown using throw.
• The thrown exception is handled by wrapping the
code into the try…catch block. If an error is
present, the catch block will execute, else only the
try block statements will get executed.
• Thus, in a programming language, there can be
different types of errors which may disturb the
proper execution of the program
• Types of Errors
While coding, there can be three types of errors in the code:
• Syntax Error: When a user makes a mistake in the pre-defined
syntax of a programming language, a syntax error may appear.
• Runtime Error: When an error occurs during the execution of the
program, such an error is known as Runtime error. The codes which
create runtime errors are known as Exceptions. Thus, exception
handlers are used for handling runtime errors.
• Logical Error: An error which occurs when there is any logical
mistake in the program that may not produce the desired output, and
may terminate abnormally. Such an error is known as Logical error.
• Error Object
• When a runtime error occurs, it creates and
throws an Error object. Such an object can be
used as a base for the user-defined exceptions
too. An error object has two properties:
• name: This is an object property that sets or
returns an error name.
• message: This property returns an error
message in the string form.
• Exception Handling Statements
• There are following statements that handle if
any exception occurs:
• throw statements
• try…catch statements
• try…catch…finally statements.
JavaScript try…catch
• A try…catch is a commonly used statement in
various programming languages.
• Basically, it is used to handle the error-prone part
of the code.
• It initially tests the code for all possible errors it
may contain, then it implements actions to tackle
those errors (if occur).
• A good programming approach is to keep the
complex code within the try…catch statements.
• Let's discuss each block of statement individually:
try{} statement: Here, the code which needs possible error
testing is kept within the try block.
• In case any error occur, it passes to the catch{} block for
taking suitable actions and handle the error. Otherwise, it
executes the code written within.
catch{} statement: This block handles the error of the code by
executing the set of statements written within the block.
• This block contains either the user-defined exception
handler or the built-in handler.
• This block executes only when any error-prone code needs
to be handled in the try block. Otherwise, the catch block is
skipped
• Syntax:
try{
expression; //code to be written.
}
catch(error)
{
expression; // code for handling the error.
}
<html>
try…catch example
<head> Exception Handling</br></head>
<body>
<script>
try{
var a= ["34","32","5","31","24","44","67"]; //a is an array
document.write(a); // displays elements of a
document.write(b); //b is undefined but still trying to fetch its value. Thus
catch block will be invoked
}
catch(e)
{
alert("There is error which shows "+e.message); //Handling error
}
</script>
</body>
</html
Throw Statement
• Throw statements are used for throwing user-defined errors. User can define and throw their
own custom errors.
• When throw statement is executed, the statements present after it will not execute. The control
will directly pass to the catch block.
• Syntax:
throw exception;
try…catch…throw syntax
Try
{
throw exception; // user can define their own exception
}
catch(error)
{

expression; // code for handling exception.


}
The exception can be a string, number, object, or boolean value.
throw example with try…catch
<html>
<head>Exception Handling</head>
<body>
<script>
try {
throw new Error('This is the throw keyword'); //user-defined throw statement.
}
catch (e)
{
document.write(e.message); // This will generate an error message
}
</script>
</body>
</html>
• try…catch…finally statements
• Finally is an optional block of statements which is executed after the
execution of try and catch statements. Finally block does not hold for the
exception to be thrown. Any exception is thrown or not, finally block code,
if present, will definitely execute. It does not care for the output too.
• Syntax:
• try{
• expression;
• }
• catch(error){
• expression;
• }
• finally{
• expression; } //Executable code

try…catch…finally example
<html>
<head>Exception Handling</head>
<body>
<script>
try{
var a=2;
if(a==2)
document.write("ok");
}
catch(Error){
document.write("Error found"+e.message);
}
finally{
document.write("Value of a is 2 ");
}
</script>
</body>
</html>
JavaScript Form Validation
• It is important to validate the form submitted by
the user because it can have inappropriate values.
So, validation is must to authenticate user.
• JavaScript provides facility to validate the form
on the client-side so data processing will be faster
than server-side validation.
• Most of the web developers prefer JavaScript
form validation.
• Through JavaScript, we can validate name,
password, email, date, mobile numbers and more
fields.
• JavaScript Form Validation Example
• In this example, we are going to validate the
name and password.
• The name can’t be empty and password can’t
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="return 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" name="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"></span><br/>
<input type="submit" value="submit">
</form>
• JavaScript validation with image
• Let’s 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.gif'/>";
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='checked.gif'/>";
}
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="password" name="p
assword"/>
<span id="passwordloc"></span></td></tr>
<tr><td colspan="2"><input type="submit" value="register"/></td><
/tr>
</table>
</form
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.
<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 email address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>
JAVASCRIPT BUILT IN OBJECTS
• 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)
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).
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
• The .length property returns the length of an array.
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.
Let's see the example of creating array directly.
<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>
Output of the above example
Arun
Varun
John
3) 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 explicitly.
The example of creating object by array constructor is given below.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
• Output of the above example
Jai
Vijay
Smith
Methods Description
concat()
copywithin()
JavaScript Array Methods
It returns a new array object that contains two or more merged arrays.

It copies the part of the given array with its own elements and returns the modified array.

It creates an iterator object and a loop that iterates over each key/value pair.
entries()
It determines whether all the elements of an array are satisfying the provided function conditions.
every()
It creates a new array carrying sub-array elements concatenated recursively till the specified depth.
flat()
It maps all array elements via mapping function, then flattens the result into a new array.
flatMap()
It fills elements into an array with static values.
fill()
It creates a new array carrying the exact copy of another array element.
from()
It returns the new array containing the elements that pass the provided function conditions.
filter()
It returns the value of the first element in the given array that satisfies the specified condition.
find()
It returns the index value of the first element in the given array that satisfies the specified condition.
findIndex()
It invokes the provided function once for each element of an array.
forEach()
It checks whether the given array contains the specified element.
includes()
It searches the specified element in the given array and returns the index of the first match.
indexOf()
It tests if the passed value ia an array.
isArray()
It creates a new iterator object carrying values for each index in the array.
values()
join() It joins the elements of an array as a string.

keys() It creates an iterator object that contains only the keys of the array, then loops through these keys.

lastIndexOf() It searches the specified element in the given array and returns the index of the last match.

map() It calls the specified function for every array element and returns the new array

of() It creates a new array from a variable number of arguments, holding any type of argument.

pop() It removes and returns the last element of an array.

push() It adds one or more elements to the end of an array.

reverse() It reverses the elements of given array.

reduce(function, initial) It executes a provided function for each value from left to right and reduces the array to a single
value.
reduceRight() It executes a provided function for each value from right to left and reduces the array to a single
value.
some() It determines if any element of the array passes the test of the implemented function.

shift() It removes and returns the first element of an array.

slice() It returns a new array containing the copy of the part of the given array.

sort() It returns the element of the given array in a sorted order.

splice() It add/remove elements to/from the given array.

toLocaleString() It returns a string containing all the elements of a specified array.

toString() It converts the elements of a specified array into string form, without affecting the original array.

unshift() It adds one or more elements in the beginning of the given array.
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";
<script>
var str="This is string literal";
document.write(str);
</script>
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.
• Let's see the example of creating string in JavaScript by
new keyword.
<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>
hello javascript string
JavaScript String Methods
Methods Description
charAt() It provides the char value present at the specified index.

charCodeAt() It provides the Unicode value of a character present at the specified index.

concat() It provides a combination of two or more strings.

indexOf() It provides the position of a char value present in the given string.

lastIndexOf() It provides the position of a char value present in the given string by searching a character
from the last position.

search() It searches a specified regular expression in a given string and returns its position if a match
occurs.

match() It searches a specified regular expression in a given string and returns that regular expression
if a match occurs.

replace() It replaces a given string with the specified replacement.


substr() It is used to fetch the part of the given string on the basis of the specified starting position and
length.

substring() It is used to fetch the part of the given string on the basis of the specified index.

slice() It is used to fetch the part of the given string. It allows us to assign positive as well negative
index.

toLowerCase() It converts the given string into lowercase letter.

toLocaleLowerCase() It converts the given string into lowercase letter on the basis of host?s current locale.

toUpperCase() It converts the given string into uppercase letter.

toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s current locale.

toString() It provides a string representing the particular object.

valueOf() It provides the primitive value of string object.

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.
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>
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>
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>
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>
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>
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>
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>
cde
• 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>
javascript trim
• JavaScript String split() Method
<script>
var str="This is Java";
document.write(str.split(" ")); //splits the given
string.
</script>
• JavaScript Math
• The JavaScript math object provides several
constants and methods to perform
mathematical operation. Unlike date object, it
doesn't have constructors.
• JavaScript Math Methods
• Let's see the list of JavaScript Math methods
with description.
Methods Description
abs() It returns the absolute value of the given number.

acos() It returns the arccosine of the given number in radians.

asin() It returns the arcsine of the given number in radians.

atan() It returns the arc-tangent of the given number in radians.

cbrt() It returns the cube root of the given number.

ceil() It returns a smallest integer value, greater than or equal to the given number.

cos() It returns the cosine of the given number.

cosh() It returns the hyperbolic cosine of the given number.

exp() It returns the exponential form of the given number.

floor() It returns largest integer value, lower than or equal to the given number.

hypot() It returns square root of sum of the squares of given numbers.


log() It returns natural logarithm of a number.

max() It returns maximum value of the given numbers.

min() It returns minimum value of the given numbers.

pow() It returns value of base to the power of exponent.

random() It returns random number between 0 (inclusive) and 1 (exclusive).

round() It returns closest integer value of the given number.

sign() It returns the sign of the given number

sin() It returns the sine of the given number.

sinh() It returns the hyperbolic sine of the given number.

sqrt() It returns the square root of the given number

tan() It returns the tangent of the given number.

tanh() It returns the hyperbolic tangent of the given number.

trunc() It returns an integer part of the given number.


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=M
ath.sqrt(17);
</script> 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>
Random Number is: 0.056703696335612896
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=M
ath.pow(3,4);
3 to the power of 4 is: 81
</script>
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);
Floor of 4.6 is: 4
</script>
• 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>
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)
;
Round of 4.3 is: 4
</script>
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.
• Absolutevalue of 4 is: <span id="p8"></span
>
<script>
document.getElementById('p8').innerHTML=M
ath.abs(-4);
Absolute value of -4 is: 4
</script>
• JavaScript Number Object
• The JavaScript number object enables you to represent a
numeric value. It may be integer or floating-point.
JavaScript number object follows IEEE standard to
represent the floating-point numbers.
• By the help of Number() constructor, you can create
number object in JavaScript. For example:
• var n=new Number(value);
• If value can't be converted to number, it returns NaN(Not a
Number) that can be checked by isNaN() method.
• You can direct assign a number to a variable also. For
example:
• var x=102;//integer value
• var y=102.7;//floating point value
• var z=13e4;//exponent value, output: 130000
• var n=new Number(16);//integer value by nu
mber object

102 102.7 130000 16


• JavaScript Number Constants
• Let's see the list of JavaScript number
constants with description.
Constant Description

MIN_VALUE returns the largest minimum value.

MAX_VALUE returns the largest maximum value.

POSITIVE_INFINITY returns positive infinity, overflow value.

NEGATIVE_INFINITY returns negative infinity, overflow value.

NaN represents "Not a Number" value.


• JavaScript Number Methods
• Let's see the list of JavaScript number
methods with their description
Methods Description

isFinite() It determines whether the given value is a finite number.

isInteger() It determines whether the given value is an integer.

parseFloat() It converts the given string into a floating point number.

parseInt() It converts the given string into an integer number.

toExponential() It returns the string that represents exponential notation of the given number.

toFixed() It returns the string that represents a number with exact digits after a decimal point.

toPrecision() It returns the string representing a number of specified precision.

toString() It returns the given number in the form of string.


JavaScript Boolean

• JavaScript Boolean is an object that represents value


in two states: true or false. You can create the
JavaScript Boolean object by Boolean() constructor as
given below.
• Boolean b=new Boolean(value);
• The default value of JavaScript Boolean object is false.
• JavaScript Boolean Example
• <script>
• document.write(10<20);//true
• document.write(10<5);//false
• </script>
JavaScript Boolean Properties

Property Description

constructor returns the reference of Boolean function that created


Boolean object.

prototype enables you to add properties and methods in Boolean


prototype.
JavaScript Boolean Properties

Method Description

toSource() returns the source of Boolean object as a string.

toString() converts Boolean into String.

valueOf() converts other type into Boolean.

You might also like