0% found this document useful (0 votes)
49 views98 pages

BE 5 IT GECBVN BharatVainsh Unit 5 (JavaScript) WD 3151606 2023

The document is a comprehensive overview of JavaScript, detailing its role in web development alongside HTML and CSS. It covers fundamental concepts such as variables, data types, operators, control structures, functions, and objects, including built-in objects like Math and Date. Additionally, it explains the differences between Java and JavaScript, as well as various methods for input/output and type conversion.

Uploaded by

mrpatel5005
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)
49 views98 pages

BE 5 IT GECBVN BharatVainsh Unit 5 (JavaScript) WD 3151606 2023

The document is a comprehensive overview of JavaScript, detailing its role in web development alongside HTML and CSS. It covers fundamental concepts such as variables, data types, operators, control structures, functions, and objects, including built-in objects like Math and Date. Additionally, it explains the differences between Java and JavaScript, as well as various methods for input/output and type conversion.

Uploaded by

mrpatel5005
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/ 98

GUJARAT TECHNOLOGICAL

UNIVERSITY
Chandkheda, Ahmedabad
Affiliated
GOVERNMENT ENGINEERING COLLEGE
BHAVNAGAR
DEPARTMENT OF INFORMATION TECHNOLOGY

Under subject of
Web Development (3151606)
B. E. III, Semester –V (Information Technology)

UNIT-3
JavaScript
Prof.Bharat Vainsh
Academic year
2023
Ch#3
JavaScript
Overview
1. HTML to define the content of web pages
• like Builder
• It decides which element has to be display.

2. CSS to specify the layout of web pages


• like Artist
• Decides where and how will be display

3. JavaScript to program the behavior of web pages


• like Wizard
• Has a capability to make decision.
HTML Example
CSS Example
Difference between Java & JavaScript
Java JavaScript
Java is a programming language JavaScript is a Scripting language

It is an object oriented programming It is not an object oriented


language programming language. Its object
model is far different than a typical
object oriented programming language.

It is strongly typed language. It is un-typed language

Objects in java are static In JavaScript the objects are dynamic.


<script> tag
• The <script> tag is used to define a client-side script
(JavaScript).
• The <script> element either contains scripting statements, or
it
• points to an external script file through the src attribute.
• Example Code
<html>
<head>
<title>HTML script Tag</title>
</head>
<body>
<script type="text/javascript">
// Java Script Code Here
</script>
</body>
</html>
Identifiers
• Identifiers are the names given to the
variables.
• These variable holds the data value.
• It must begin with either letter or underscore
or dollar sign.
• There is no limit on the length of identifiers.
• Programmer defined variable names must not
have upper case letters.
Reserved words

break continue delete for in

return throw var with case

default else function instanceof switch

try void catch do finally

if new this typeof while


Comments
• JavaScript supports following comments
• The // used for single line
• The /* and */ used for multi-line
• The <!- - > and <-- >
Variables
1. Primitive Types :
• JavaScript defines two entities
• Primitives & Objects
• Primitives: The primitives are for storing values
• Type of Primitives are
a. Number
b. String
c. Boolean
d. Undefined
e. Null
• Objects : It is for storing the reference to the actual values.
• Type of predefined objects
a. Number
b. String
c. Boolean
Representation of Primitive and Object

10
X = 10;
X
Representation of Primitive type

Obj contains the address at


65530 10 which the value is stored

obj 65530
Representation of object type
Literals
• There are two types of literals used in JavaScript
1. Numeric literals
e.g. 10
10.3
10.0
10E3
10.2E4
10e-3
2. String literals
e.g. ‘ Rain Rain come soon’
Variable declaration
• Declare variable using reserved word var.
• Value of variable can be anything.
• It can be numeric or string or boolean
<html>
<head> <title> Variables in javascript </title> </head>
<body>
<script type=“text/javascript”> Variable declaration is done using var.
var a,b,c; Note that there is no data type required.
var string;
a=2;
b=3;
c=a+b;
output
string = “The result=“;
document.write (“ addition of 2 & 3.” + “</br>”); Addition of 2 & 3.
document.write ( string); The result=5
document.write (c);
</scipt> <body> </html>
Operators
Type Operator Meaning Example
+ Addition or Unary plus C=a+b
- Subtraction or Unary minus C=a-b
Arithmetic
* Multiplication C=a*b
/ Division C=a/b
% Mod C=a%b
< Less than a< 4
<= Less than equal to b <= 10

Relational > Greater than a > 10


>= Greater than equal to a >= 10
== Equal to x == 100
!= Not equal to m != 8
&& And 0 && 1
Logical || Or 0 || 1
Assignment = Is assigned to a=5
Increment ++ Increment by one ++i or i++
Decrement -- Decrement by one --i or i--
Typeof operator
• Typeof operator returns the primitive type of
the variables
• If the variable is of object type or null then it
returns the object.
• If a variable is declared and it is not used then
its type is undefined.
<html> output
<head> <title> Typeof Demo </title></head>
<body> Mynum = number
<script type=“text/javascript”> Myboolean = boolean
var Mystr=“computer”; Myobj = object
var Mynum=100; Myobj1 = object
var Myboolean=false; Mynum1 = undefined
var Mynum1; // declared but not assigned any value Mystr = string
var Myobj1;
Myobj=new Date();
Myobj1=null; // null is taken as a object type
document.write(“Mynum=“+typeof(Mynum)+”<br/>”);
document.write(“Myboolean=“+typeof(Myboolean)+”<br/>”);
document.write(“Myobj=“+typeof(Myobj)+”<br/>”);
document.write(“Myobj1=“+typeof(Myobj1)+”<br/>”);
document.write(“Mynum1=“+typeof(Mynum1)+”<br/>”);
document.write(“Mystr=“+typeof(Mystr)+”<br/>”);
</script>
</body>
</html>
Implicit Type Conversion
• javascript supports the implicit type conversions.
E.g. “Survey_Number” + 10

This is string This is Number


Result of above operation will get a string
“Survey_Number 10“
• JavaScript support such automatic conversion.
• This technique of implicit conversions is called coercions.
E.g. 5 * “12” will return 60
But if we take 5 * “Hello” will return NaN
Explicit Type Conversion
• One can forcefully perform the type conversion in JavaScript.
• Numeric value can be converted to string type using toString method.
• E.g. var my_num=2;
var my_str;
my_str=my_num.toString();
Resultant value of my_str becomes “2”
• In JavaScript explicit type conversion can be done as
i. Boolean(my_val) Convert the my_val to Boolean type
ii. Number(my_val) Convert the my_val to Number type
iii. String(my_val) Convert the my_val to String type
• There are two methods that are used to separate out the numeric data
from alphanumeric
i. parseInt() E.g. parseInt(“12abc”); return 12
ii. parseFloat() E.g. parseFloat(“12.25abc”); return 12.25
Input and Output
• The property write of object window is used to display something on
the screen.
• The methods alert, prompt and confirm are useful for handling
screen output and keyboard input.
1. document.write Property :
• E.g. document.write(“Grate India”); or document.write(my_msg);
2. The Popup Boxes :
Important features of javascript is its interactivity with the user.
This page says :
alert box: In this type of
popup box some message Hello World
will be displayed.
ok
Conti…
Confirm box : In this type of
This page says :
popup box in which the
message about confirmation Are you sure ?
will be displayed. Hence it
should have two buttons ok ok Cancel
and cancel.

Prompt box : is a type of This page says :


Enter Name
popup box which display a text
window in which the user can
enter something. Hence it has ok Cancel
two buttons ok and Cancel.
Conditions, Loops and Repetition
Control structure is essential part of any
programming language which is required to
control the logic of your program.

• if statement
• while
• do – while
• for
• switch case
• break
• Continue
Selection Statement
• if the syntax of if is
if (condition)
statement if the condition is true
• if ….. else the syntax for if….else
if (condition)
statement if the condition is true
else
statement if the condition is false
• if…..else if the syntax of if….else if
if (condition)
statement if the condition is true
else if (condition)
statement if another condition is true
else if (condition)
statement if another condition is true
…….
else statement
Functions
• A JavaScript function is a block of code designed to perform a
particular task.
• A JavaScript function is executed when "something“ invokes it.
A JavaScript function is defined with the function keyword,
followed by a name, followed by parentheses ().
• The parentheses may include parameter names separated by
commas: (parameter1, parameter2, ...)
Code
function myFunction(p1, p2) {
return p1 * p2;
}
Conti…
• The code to be executed, by the function, is placed inside curly brackets.
• When JavaScript reaches a return statement, the function will stop
executing.
• Separate functions can be created for each separate task.
• Ultimately helps in finding the bug from the program efficiently.
• Can define the function any where in the script either in head or body or
in both .
a. Function declaration
b. Function call
c. Returning value from the function
d. Passing the parameters to the function
e. Passing an array to the function
JavaScript Objects
• An object is just a special kind of data, with properties and methods.
Accessing Object Properties :
• Properties are the values associated with an object.
• The syntax for accessing the property of an object is below
E.g. objectName.propertyName
Accessing Object Methods
• Methods are the actions that can be performed on objects.
• You can call a method with the following syntax.
objectName.methodName()
• This example uses the toUpperCase method of the String object to convert
string to upper case:
var message="Hello World!";
var x=message.toUpperCase();
JavaScript’s inbuilt Objects
• JavaScript comes with some inbuilt objects
which are,
• String
• Date
• Array
• Boolean
• Math
• RegExp
• etc….
Math Object in JavaScript
• The Math object allows you to perform mathematical tasks.
• The Math object includes several mathematical constants and
methods.
• Example for using properties/methods of Math:

Code
<script>
var x=Math.PI;
var y=Math.sqrt(16);
</script>
Math Object (Cont.)
• Math object has some properties which are,
Properties Description

E Returns Euler's number(approx.2.718)


LN2 Returns the natural logarithm of 2 (approx.0.693)
LN10 Returns the natural logarithm of 10 (approx.2.302)
LOG2E Returns the base-2 logarithm of E (approx.1.442)
LOG10E Returns the base-10 logarithm of E (approx.0.434)
PI Returns PI(approx.3.14)
SQRT1_2 Returns square root of ½
SQRT2 Returns square root of 2
Math Methods (Cont.)
Method Description
sqrt(x) Returns the square root of x
abs(x) Returns the absolute value of x
ceil(x) Returns x, rounded upwards to the nearest integer
floor(x) Returns x, rounded downwards to the nearest integer
log(x) Returns the natural logarithm(base E) of x
pow(x,y) Returns the value of x to the power of y
max(x,y, Returns the number with the highest value
z,...,n)
sin(x) Returns the sine of x (x is in radians)
cos(x) Returns the cosine of x (x is in radians)
tan(x) Returns the tan of x (x is in radians)
exp(x) Returns the value of Ex
Number Object
Property Meaning
MAX_VALUE Largest possible number gets displayed.
MIN_VALUE Smallest possible number gets displayed.
NaN When not a number then NaN is displayed
PI The value of PI gets displayed
POSITIVE_INFINITY The positive infinity gets displayed
NEGATIVE_INFINTY The negative infinity gets displayed.
Date Object
• This object is used for date and time.
• This date and time value is based on computer’s local time
(System’s time) or it can be based on GMT(Greenwich Mean
Time)
• Now a days GMT is also known as UTC
• Universal C0-0rdinated Time is basically a world time
standard.
Method Meaning
getTime() Returns no. Of milliseconds. This value is difference
between the current time and the time value from 1st
January 1970
getDate() Returns current date based on computers local time.
getUTCDate() Returns the current date obtain from UTC
Date Object (Conti...)
Method Meaning
getDay() Returns the current day. Day number from 0 to 6.i.g. From Sunday to
Saturday.
getUTCDay() Return the current day based on UTC. The day number is from 0 to 6.
i.g. From Sunday to Saturday
getHours() Returns the hour value ranging from 0 to 23, based on local time.
getMinutes() Returns the minute value ranging from 0 to 999, based on UTC
timing Zone.
getSeconds() Returns the second value ranging from 0 to 59, based on UTC timing
zone.
setDate() This function helps to set the desired date using local timing zone.
setHour(hr,min This function is help to set desired time using local or UTC timing
ute,second,ms zone. Only hour parameter is compulsory and rest all are the
) optional parameter.
Boolean Object
• Used when we want to represent true and
false values.
Strings
• A string can be defined as a sequence of letters, digits,
punctuation and so on.
• A string in a JavaScript is wrapped with single or double
quotes
• Strings cab be joined together with the + operator, which is
called concatenation.
• For Example,
• mystring = “my college name is ” + “GEC Bhavnagar”;
• As string is an object type it also has some useful features.
For Example,
lenStr = mystring.length;
Which returns the length of the string in integer
Strings (Conti..)
Method Meaning
concat(str) This method concatenates the two string
charAt(index_val) This method will return the character specified by value index_val.
Substring(begin,e This method returns the substring specified by begin and end
nd) character.
toLowerCase() This function is used to convert all the uppercase letters to lower
case.
toUpperCase() This function is used to convert all the lowercase letters to
uppercase.
valueOf() This method retunes the value of the string.
User - Defined Objects
• JavaScript allows you to create your own objects.
• The first step is to use the new operator.
var myObj= new Object();

• This creates an empty object.


• This can then be used to start a new object that
you can then give new properties and methods.
Example
<script>
Function myfun()
{
var obj=new Object();
Obj.Name=“James”;
Obj.Age=“19”;
Alert(obj.Name);
Alert(obj.Age);
}
<script>

<button name=“clickon” onlclick=myfun();”>Click me</Button>


Document Object Model (DOM)
• The Document Object Model is a platform- and
language-neutral
interface that will allow programs and scripts to
dynamically access and update the content, structure
and style of documents.
• The window object is the primary point from which
most other
objects come.
• From the current window object access and control
can be given
to most aspects of the browser features and the
HTML document.
DOM (Conti...)
• When we write : document.write(“Hello World”);
• We are actually writing :
window.document.write(“Hello World”);
• The window is just there by default
• This window object represents the window or
frame that displays the document and is the
global objet in client side programming for
JavaScript.
• All the client side objects are connected to the
window object.
getElementById()
• When we suppose to get the reference of the element from
HTML
• in JavaScript using id specified in the HTML we can use this
method. HTML
<html>
• Example : <body>
<input type=“text” id=“myText”>
</body>
</html>
JavaScript
<script>
function myFunction()
{
alert(document.getElementById(“myText”).value);
}
</script>
getElementsByName()
• When we suppose to get the reference of the elements from
HTML in JavaScript using name specified in the HTML we can
use this method.
• It will return the array of elements with the provided name.
• Example :
HTML JavaScript
<html> <script>
<body> function myFunction()
<input type=“text” {
name=“myText”> a=document.getElementsByName(“myText”)[0];
</body> alert(a.value);
</html> }
</script>
getElementsByTagName()
• When we suppose to get the reference of the elements from
HTML in JavaScript using name of the tag specified in the
HTML we can use this method.
• It will return the array of elements with the provided tag
name.
• Example :

JavaScript
HTML
<script>
<html>
function myFunction() {
<body>
a=document.getElementsByTagName(“input”);
<input type=“text” name=“uname”>
alert(a[0].value);
<input type=“text” name=“pword”>
alert(a[1].value);
</body>
}
</html>
</script>
DHTML
• Dynamic HyperText Markup Language (DHTML)
HTML DHTML

HyperText Markup Language Dynamic Hyper Text Markup Language


Used to create static web pages. Used to create dynamic web pages.
It consist of simple HTML tags. It is made up of HTML Tags + CSS
+Javascript
HTML does not allow to alter the text But in DHTML you can alter the text and
and graphics on the web page unless graphics of the web page and for that
web page gets changed. matter you need not to change the
entire web page.

Creation of HTML web pages is simple Creation of DHTML is complex but more
but not interactive. interactive.
JavaScript Array
• JS Array
• Array is special type of variable which can store
multiple values as well as each value is associated
with numeric index starting with zero.
• Value
index 010 120 230 340 450
That allows to store more that one value or a group
of values under a single variable name.
Array can store any valid value.
JavaScript Array
Java script array literal
• Var emp=[“X”,”Y”,”Z”];
• For(i=0;i<emp.length;i++){
• Document.write(emp[i] +”</br>”);
• }
Javascript array directly new keyword
• Var I;
• Var emp =new Array();
• Emp[0]=“x”;
• Javascript array constructor new keyword
• Var emp=new Array(“x”,”y”,”z”);
Creating Array
• Var myarray=[element 0,element 1…element N]
• Var colors=[“red”,”green”,”blue”];
• Example
var fruits=[“Apple”,”Banana”,”Mango”];
document.write(fruits.length);
for(var i=0;i<fruits.length;i++)
{ document.write(fruits[i]+”<br>”);
}
Array
• How to store some array elements in array.
• A= new Array(5); //creation of array
For(i=0;i<5;i++)
{a[i]=i;
document.write(a[i]+”<br>”);//displaing array
}
B=new Array(11,22,33,44);
Days=new Array();
Days[0]=“sunday”;
For(in days)
{ document.write(Days[i]+”</br>”);
}
Events
• What is an 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.
Events
• An activity that represent change in the environment.
• E.g. Mouse click, pressing particular key of keyboard
• Such events are called Intrinsic events.
• Event handler is a script that gets executed in
response to these events.
• Javascript support such special typeof programming in
which events may occur and these events get
responded by executing the event handlers.
• Events are specified in lowercase letters and these are
case-sensitive.
• The process of connecting event handler to an event is
called event Registration.
• 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.
Event, Attribute and Tags
Events Attributes Meaning Associated Tags
blur onblur Losing the focus <button>
<input>
<a>
<textarea>
<select>
change onchange On occurence of <input>
some change <textarea>
<select>
click onclick When user clicks <a>
the mouse button <input>
dbclick ondbclick When user double <a>
clicks the mouse <input>
<button>
focus onfocus When user acquires <a>
the input focus <input>
<select>
<textarea>
Conti...
Event Attribute Meaning Associated Tags
keyup onkeyup When user releases <input>
the from the <button>
keyboard <textarea>
keydown onkeydown When user presses <input>
the key <button>
<textarea>
mousedown onmousedown When user clicks Form element such
the left mouse as input,button etc
button
mouseup onmouseup When user releases Form element such
the left mouse as input,button
button etc..
mousemove onmousemove When user moves Form element...
the mouse
Conti...
Event Attribute Meaning Associated Tags
load onload After getting the <body>
document loaded
reset onreset When the reset <form>
button is clicked
submit onsubmit When the submit <form>
button is clicked
select onselect On selection <input>
<textarea>

unload onunload When user exits the <body>


document
Example-1
<html>
<head>
<script>
function hiThere()
{
alert('Hi there!');
}
</script>
</head>

<body>
<form>
<input type="button" name="button" value="Go"
onclick="hiThere()"></input>
</form>
</body>
</html>
Example-2
<script>
var a = 0;
var b = 0;
var c = 0;

function changeBackground()
{
var x = document.getElementById('bg');
bg.style.backgroundColor = 'rgb('+a+', '+b+', '+c+')';

a += 1;
b += a + 1;
c += b + 1;

if (a > 255) a = a - b;
if (b > 255) b = a;
if (c > 255) c = b;
}
</script>
</head>
<body>
<input id="bg" onkeyup="changeBackground()" placeholder="write something"
style="color:#fff">
</body>
Example-3
<script>
function hov() {
var e = document.getElementById('hover');
e.style.display = 'none'; }
</script>
</head>

<body>
<div id="hover" onmouseover="hov()"
style="background-
color:red;height:300px;width:300px;">
</div>
</body>
Example-4
<html>
<head></head>
<title></title>

<body>
<input type="number" onchange="alert(this.value)" >

</body>
</html>
Example-5
<body>
<!-- <img onload="alert('Image completely loaded')"
alt="Smart Learning-Logo"
src="https://bharatvainshit.in">-->

<script>
function sample()
{
alert("welcome");

}
</script>
<body onload="sample()">
</body>
JavaScript Cookies
What is a Cookie
A cookie is a small text file that lets you store a small amount of
data (nearly 4KB) on the user's computer. They are typically used
for keeping track of information such as user preferences that
the site can retrieve to personalize the page when user visits the
website next time.
Cookies are an old client-side storage mechanism that was
originally designed for use by server-side scripting languages
such as PHP, ASP, etc. However, cookies can also be created,
accessed, and modified directly using JavaScript, but the process
is little bit complicated and messy.
Tip: A cookie can be up to 4 KB, including its name and values,
cookies that exceed this length are trimmed to fit. Also, each
time the browser requests a page to the server, all the data in
the cookie is automatically sent to the server within the request.
Warning: Don't store sensitive data such as a password or credit
card information in cookies since it could potentially be
manipulated by the malicious user.
JavaScript Cookies
Creating a Cookie in JavaScript
In JavaScript, you can create, read, and delete
cookies with the document.cookie property.
This property represents all the cookies
associated with a document.
To create or store a new cookie, assign a
name=value string to this property, like this:
document.cookie = "firstName=James";
A cookie value cannot contain semicolons,
commas, or spaces.
JavaScript Cookies
ExampleTry this code »
function setCookie(name, value, daysToLive) {
// Encode value in order to escape semicolons, commas, and whitespace
var cookie = name + "=" + encodeURIComponent(value);

if(typeof daysToLive === "number") {


/* Sets the max-age attribute so that the cookie expires
after the specified number of days */
cookie += "; max-age=" + (daysToLive*24*60*60);

document.cookie = cookie;
}
}
By default, a cookie is available to all web pages in the same directory or any
subdirectories of that directory. However, if you specify a path the cookie is
available to all web pages in the specified path and to all web pages in all
subdirectories of that path.
For example, if the path is set to / the cookie is available throughout a
website, regardless of which page creates the cookie.
ExampleTry this code »
function checkCookie() {
// Get cookie using our custom function
var firstName = getCookie("firstName");

if(firstName != "") {
alert("Welcome again, " + firstName); }
else {
firstName = prompt("Please enter your first name:");
if(firstName != "" && firstName != null) {
// Set cookie using our custom function
setCookie("firstName", firstName, 30); } }}
Updating a Cookie
The only way to update or modify a cookie is to create another cookie with
the same name and path as an existing one. Creating a cookie with the same
name but with a different path then that of an existing one will add an
additional cookie. Here's an example:

ExampleTry this code »


// Creating a cookie
document.cookie = "firstName=James; path=/; max-age=" + 30*24*60*60;
// Updating the cookie
document.cookie = "firstName=Alexander; path=/; max-age=" +
365*24*60*60;
Deleting a Cookie
To delete a cookie, just set it once again using the same name,
specifying an empty or arbitrary value, and setting its max-age
attribute to 0. Remember that if you've specified a path, and
domain attribute for the cookie, you'll also need to include them
when deleting it.
ExampleTry this code »
// Deleting a cookie
document.cookie = "firstName=; max-age=0";
// Specifying path and domain while deleting cookie
document.cookie = "firstName=; path=/; domain=example.com; max-age=0";
However, to delete a cookie using the expires attribute, simply set its value (i.e. the
expiration date) to a date that has already passed, as demonstrated below.
document.cookie = "firstName=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
JavaScript 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.
Validation (Cont.)
• Form validation generally performs two functions.
1. Basic Validation
• Emptiness
• Confirm Password
• Length Validation etc……
• 2. Data Format Validation
Secondly, the data that is entered must be checked for
correct form and value.
• Email Validation
• Mobile Number Validation
• Enrollment Number Validation etc….
<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>
<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>
<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>
JavaScript Regular Expressions
• What is Regular Expression
• Regular Expressions, commonly known as "regex"
or "RegExp", are a specially formatted text strings
used to find patterns in text.
• Regular expressions are one of the most powerful
tools available today for effective and efficient
text processing and manipulations.

• For example, it can be used to verify whether the


format of data i.e. name, email, phone number,
etc. entered by the user is correct or not, find or
replace matching string within text content, and
so on.
Let's begin with a brief overview of the commonly used JavaScript's built-in
methods for performing pattern-matching before delving deep into the world
of regular expressions.

Function What it Does

exec() Search for a match in a string. It returns an array of information or


null on mismatch.
test() Test whether a string matches a pattern. It returns true or false.
search() Search for a match within a string. It returns the index of the first
match, or -1 if not found.
replace() Search for a match in a string, and replaces the matched
substring with a replacement string.
match() Search for a match in a string. It returns an array of information or
null on mismatch.
split() Splits up a string into an array of substrings using a regular
expression.
Note: The methods exec() and test() are RegExp methods that takes a string
as a parameter, whereas the methods search(), replace(), match() and split()
are String methods that takes a regular expression as a parameter.
The literal syntax uses forward slashes (/pattern/) to wrap the regular
expression pattern, whereas the constructor syntax uses quotes ("pattern").
The following example demonstrates both ways of creating a regular
expression that matches any string that begins with "Mr.".

Example
// Literal syntax
var regex = /^Mr\./;

// Constructor syntax
var regex = new RegExp("^Mr\\.");
As you can see, the regular expression literal syntax is shorter and easier to
read. Therefore it is preferable to use the literal syntax. We'll also use it
throughout this tutorial.

Note: When using the constructor syntax, you've to double-escape special


characters, which means to match "."
you need to write "\\." instead of "\.". If there is only one backslash, it would
be interpreted by JavaScript's string parser as an escaping character and
removed.
You can also define a range of characters by using the hyphen (-)
character inside a character class, like [0-9]. Let's look at some
examples of the character classes:

RegExp What it Does


[abc] Matches any one of the characters a, b, or c.
[^abc] Matches any one character other than a, b, or c.
[a-z] Matches any one character from lowercase a to lowercase z.
[A-Z] Matches any one character from uppercase a to uppercase z.
[a-Z] Matches any one character from lowercase a to uppercase Z.
[0-9] Matches a single digit between 0 and 9.
[a-z0-9] Matches a single character between a and z or between 0 and
9.
The following example will show you how to find whether a pattern
exists within a string or not using the regular expression with the
JavaScript test() method:
ExampleRun this code »
var regex = /ca[kf]e/;
var str = "He was eating cake in the cafe.";

// Test the string against the regular expression


if(regex.test(str)) {
alert("Match found!");
} else {
alert("Match not found.");
}
Further, you can add the global flag g to a regular expression to find all
matches in a string:

ExampleRun this code »


var regex = /ca[kf]e/g;
var str = "He was eating cake in the cafe.";
var matches = str.match(regex);
alert(matches.length); // Outputs: 2
Predefined Character Classes
Some character classes such as digits, letters, and whitespaces are
used so frequently that there are shortcut names for them.

The following table lists those predefined character classes:


Shortcut What it Does
. Matches any single character except newline \n.
\d matches any digit character. Same as [0-9]
\D Matches any non-digit character. Same as [^0-9]
\s Matches any whitespace character (space, tab, newline or
carriage return character).
Same as [ \t\n\r]
\S Matches any non-whitespace character.
Same as [^ \t\n\r]
\w Matches any word character (definned as a to z, A to Z,0 to 9,
and the underscore).
Same as [a-zA-Z_0-9]
\W Matches any non-word character. Same as [^a-zA-Z_0-9]
Example
var regex = /\s/g;
var replacement = "-";
var str = "Earth revolves around\nthe\tSun";

// Replace spaces, newlines and tabs


document.write(str.replace(regex, replacement) +
"<hr>");

// Replace only spaces


document.write(str.replace(/ /g, "-"));
JSON
JSON: JavaScript Object Notation.
JSON is a syntax for storing and exchanging data.
JSON is text, written with JavaScript object notation.
JSON is a lightweight data-interchange format
JSON is "self-describing" and easy to understand
JSON is language independent *

JavaScript Object Notation is a standard text-based


format for representing structured data based on
JavaScript object syntax.
It is commonly used for transmitting data in web
applications (e.g., sending some data from the server to
the client, so it can be displayed on a web page, or vice
versa).
Why use JSON?
Since the JSON format is text only, it can easily
be sent to and from a server, and used as a data
format by any programming language.
JavaScript has a built in function to convert a
string, written in JSON format, into native
JavaScript objects:
JSON.parse()
So, if you receive data from a server, in JSON
format, you can use it like any other JavaScript
object.
JSON Syntax Rules
JSON syntax is derived from JavaScript object
notation syntax:
 Data is in name/value pairs
 Data is separated by commas
 Curly braces hold objects
 Square brackets hold arrays
JSON Data - A Name and a Value
JSON data is written as name/value pairs.
A name/value pair consists of a field name (in double
quotes), followed by a colon, followed by a value:
Example
"name":"John"
JSON Example
{"employees":[
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Anna", "lastName":"Smith" },
{ "firstName":"Peter", "lastName":"Jones" }
]}
Array as JSON
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myArr[0];
}
};
xmlhttp.open("GET", "json_demo_array.txt", true);
xmlhttp.send();
Exchanging Data
When exchanging data between a browser and a
server, the data can only be text.
JSON is text, and we can convert any JavaScript
object into JSON, and send JSON to the server.
We can also convert any JSON received from the
server into JavaScript objects.
This way we can work with the data as
JavaScript objects, with no complicated parsing
and translations.
Sending Data
If you have data stored in a JavaScript object,
you can convert the object into JSON, and send
it to a server:
Example
var myObj = {name: "John", age: 31, city: "New
York"};
var myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" +
myJSON
Receiving Data
If you receive data in JSON format, you can
convert it into a JavaScript object:
Example
var myJSON = '{"name":"John", "age":31,
"city":"New York"}';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML
= myObj.name;
Storing Data
When storing data, the data has to be a certain format, and
regardless of where you choose to store it, text is always one of
the legal formats.
JSON makes it possible to store JavaScript objects as text.

Example
Storing data in local storage
// Storing data:
myObj = {name: "John", age: 31, city: "New York"};
myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);

// Retrieving data:
text = localStorage.getItem("testJSON");
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name;
Object concepts in JavaScript
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 concepts in JavaScript
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;
For example − The following code gets the document title
using the "title" property of the document object.
var str = document.title;
Object concepts in JavaScript
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");
Object concepts in JavaScript
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;

For example − The following code gets the document title


using the "title" property of the document object.
var str = document.title;
Object concepts in JavaScript
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");
Object concepts in JavaScript
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.
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
}
References
• E-Books:
Web Technologies, Black Book, Dreamtech Press
PHP: The Complete Reference By Steven Holzner, McGrawhill

• Website :
1. https://www.bharatvainsh.in/
2. https://smarteportal.blogspot.com/
3. https://www.w3schools.com/
4. https://www.javatpoint.com/
5. https://www.studentstutorial.com/
6. https://www.tutorialspoint.com/seo/index.htm
7. https://javascript.info/
8. https://www.guru99.com/
9. https://www.tutorialspoint.com/php/
10. https://www.codecademy.com/catalog/subject/web-development

• Faculty Guide : Prof. Bharat Vainsh

You might also like