100% found this document useful (1 vote)
259 views

6 Cse - Cs8651 Ip Unit 2

JavaScript is a lightweight, interpreted programming language that allows for dynamic web pages and client-side scripting interactions by integrating with HTML and complementing Java. JavaScript code is executed in the browser and can be used to validate user input before form submission, provide immediate feedback, increase interactivity through event handling, and dynamically create rich interfaces.

Uploaded by

Sanjay S
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
100% found this document useful (1 vote)
259 views

6 Cse - Cs8651 Ip Unit 2

JavaScript is a lightweight, interpreted programming language that allows for dynamic web pages and client-side scripting interactions by integrating with HTML and complementing Java. JavaScript code is executed in the browser and can be used to validate user input before form submission, provide immediate feedback, increase interactivity through event handling, and dynamically create rich interfaces.

Uploaded by

Sanjay S
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/ 91

Please read this disclaimer before

proceeding:
This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document
through email in error, please notify the system manager. This document contains
proprietary information and is intended only to the respective group / learning
community as intended. If you are not the addressee you should not disseminate,
distribute or copy through e-mail. Please notify the sender immediately by e-mail
if you have received this document by mistake and delete this document from
your system. If you are not the intended recipient you are notified that disclosing,
copying, distributing or taking any action in reliance on the contents of this
information is strictly prohibited.
CS8651
Internet Programming

Department : CSE
Batch/Year : 2018 -22 / III
Created by : A. JASMINE GILDA,
Assistant Professor.
TABLE OF CONTENTS

S. No. Topic

1 Course Objectives

2 Pre-Requisites

3 Syllabus

4 Course outcomes

5 CO- PO/PSO Mapping

6 Lecture Plan

7 Activity based learning

8 Lecture Notes

9 Assignments

10 Online Certifications

11 Assessment Schedule

1 Text Books & Reference Books

5
COURSE OBJECTIVE

To understand different Internet Technologies.

To learn java-specific web services architecture


PRE REQUISITES

CS8392 Object Oriented Programming


CS8591 Computer Networks

7
SYLLABUS

CS8651 INTERNET PROGRAMMING LTPC


3003
UNIT I WEBSITE BASICS, HTML 5, CSS 3, WEB 2.0 9
Web Essentials: Clients, Servers and Communication – The Internet – Basic Internet
protocols – World wide web – HTTP Request Message – HTTP Response Message –
Web Clients – Web Servers – HTML5 – Tables – Lists – Image – HTML5 control
elements – Semantic elements – Drag and Drop – Audio – Video controls - CSS3 –
Inline, embedded and external style sheets – Rule cascading – Inheritance –
Backgrounds – Border Images – Colors – Shadows – Text – Transformations –
Transitions – Animations.
UNIT II CLIENT SIDE PROGRAMMING 9
Java Script: An introduction to JavaScript–JavaScript DOM Model-Date and Objects,-
Regular Expressions- Exception Handling-Validation-Built-in objects-Event Handling-
DHTML with JavaScript- JSON introduction – Syntax – Function Files – Http Request –
SQL.
UNIT III SERVER SIDE PROGRAMMING 9
Servlets: Java Servlet Architecture- Servlet Life Cycle- Form GET and POST actions-
Session Handling- Understanding Cookies- Installing and Configuring Apache Tomcat
Web Server- DATABASE CONNECTIVITY: JDBC perspectives, JDBC program example -
JSP: Understanding Java Server Pages-JSP Standard Tag Library (JSTL)-Creating
HTML forms by embedding JSP code.
UNIT IV PHP and XML 9
An introduction to PHP: PHP- Using PHP- Variables- Program control- Built-in
functions- Form Validation- Regular Expressions - File handling – Cookies -
Connecting to Database. XML: Basic XML- Document Type Definition- XML Schema
DOM and Presenting XML, XML Parsers and Validation, XSL and XSLT Transformation,
News Feed (RSS and ATOM).
UNIT V INTRODUCTION TO AJAX and WEB SERVICES 9
AJAX: Ajax Client Server Architecture-XML Http Request Object-Call Back Methods;
Web Services: Introduction- Java web services Basics – Creating, Publishing, Testing
and Describing a Web services (WSDL)-Consuming a web service, Database Driven
web service from an application –SOAP.
TOTAL: 45 PERIODS
COURSE OUTCOMES

CO Course outcome(CO) - Statements

Construct a basic website using HTML and Cascading Style


CO - 1
Sheets.

Build dynamic web page with validation using Java Script


CO - 2
objects and by applying different event handling mechanisms.

CO - 3 Develop server side programs using Servlets and JSP.

Construct simple web pages in PHP and to represent data in


CO - 4
XML format.

Use AJAX and web services to develop interactive web


CO - 5
applications

CO - 6 Use various client and server interfacing tools


CO-PO/PSO Mapping

C PO PO PO PO PO PO PO PO PO PO PO PO PSO PS PSO
O 1 2 3 4 5 6 7 8 9 10 11 12 1 O2 3

1 3 3 3 - 3 - - - 2 - - - 3 3 3
2 3 3 3 - 3 - - - 2 - - 3 3 3 3
3 3 3 3 - 3 - - - 2 - - 3 3 3 3
4 3 3 3 - 3 - - - 2 - - 3 3 3 3
5 3 3 3 - 3 - - - 2 - - 3 3 3 3
6 3 3 3 - 3 - - - 2 - - 3 3 3 3
LECTURE PLAN – UNIT II

UNIT II CLIENT SIDE PROGRAMMING

Java Script: An introduction to JavaScript–JavaScript DOM Model-Date and


Objects,-Regular Expressions- Exception Handling-Validation-Built-in objects-
Event Handling- DHTML with JavaScript- JSON introduction – Syntax –
Function Files – Http Request – SQL.

Session Mode of
Topics to be covered Reference
No. delivery

1 Java Script: An introduction to JavaScript PPT 1

2 JavaScript DOM Model-Date and Objects PPT 1

3 Regular Expressions PPT 1

4 Exception Handling-Validation-Built-in objects PPT 1

5 Event Handling DHTML with JavaScript PPT 1

6 JSON introduction – Syntax PPT 1

7 JSON - Function Files PPT 1

8 Http Request PPT 1

9 SQL PPT 1

CONTENT BEYOND THE SYLLABUS :-


NPTEL/OTHER REFERENCES / WEBSITES : http://nptel.ac.in

1. Deitel and Deitel and Nieto, ―Internet and World Wide Web - How to

Program, Prentice Hall, 5th Edition, 2011.

2. Jeffrey C and Jackson, “Web Technologies A Computer Science Perspective”,

Pearson Education, 2011.

NUMBER OF PERIODS: Planned: 9 Actual:


DATE OF COMPLETION: Planned: 18.03.2021 Actual:
REASON FOR DEVIATION (IF ANY) :
CORRECTIVE MEASURES 11
ACTIVITY BASED LEARNING – UNIT II

WEBSITE DEVELOPMENT

Students must form a group of 2 to 3 members. Each team must


develop a website and present it to other teams. Discussion will be
done based on the components used.
Unit II

CLIENT SIDE PROGRAMMING


JAVASCRIPT

INTRODUCTION
Javascript is a dynamic computer programming language. It is lightweight and most
commonly used as a part of web pages, whose implementations allow client-side script
to interact with the user and make dynamic pages. It is an interpreted programming
language with object-oriented capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript,
possibly because of the excitement being generated by Java. JavaScript made its first
appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose
core of the language has been embedded in Netscape, Internet Explorer, and other
web browsers.
The ECMA-262 Specification defined a standard version of the core JavaScript
language.
• JavaScript is a lightweight, interpreted programming language.
• Designed for creating network-centric applications.
• Complementary to and integrated with Java.
• Complementary to and integrated with HTML.
• Open and cross-platform
Client-side JavaScript
• Client-side JavaScript is the most common form of the language. The script should
be included in or referenced by an HTML document for the code to be interpreted by
the browser.
• It means that a web page need not be a static HTML, but can include programs that
interact with the user, control the browser, and dynamically create HTML content.
• The JavaScript client-side mechanism provides many advantages over traditional CGI
server-side scripts. For example, you might use JavaScript to check if the user has
entered a valid e-mail address in a form field.
• The JavaScript code is executed when the user submits the form, and only if all the
entries are valid, they would be submitted to the Web Server.
• JavaScript can be used to trap user-initiated events such as button clicks, link
navigation, and other actions that the user initiates explicitly or implicitly.
Advantages of JavaScript
 Less server interaction − You can validate user input before sending the page off
to the server. This saves server traffic, which means less load on your server.
 Immediate feedback to the visitors − They don't have to wait for a page reload
to see if they have forgotten to enter something.
 Increased interactivity − You can create interfaces that react when the user
hovers over them with a mouse or activates them via the keyboard.
 Richer interfaces − You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.

Limitations of JavaScript
 Client-side JavaScript does not allow the reading or writing of files. This has been
kept for security reason.
 JavaScript cannot be used for networking applications because there is no such
support available.
 JavaScript doesn't have any multithreading or multiprocessor capabilities.

JavaScript can be implemented using JavaScript statements that are placed within
the<script>... </script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within you web
page, but it is normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between
these tags as a script. A simple syntax of your JavaScript will appear as follows.
The script tag takes two important attributes –
• Language − This attribute specifies what scripting language you are using. Typically,
its value will be javascript. Although recent versions of HTML (and XHTML, its
successor) have phased out the use of this attribute.
• Type − This attribute is what is now recommended to indicate the scripting language
in use and its value should be set to "text/javascript".

So your JavaScript segment will look like −


<script language="javascript" type="text/javascript">
JavaScript code
</script>
INCLUDING JAVASCRIPT 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.
In the following section, we will see how we can place JavaScript in an HTML file in different ways.
JavaScript in <head>...</head> section
If you want to have a script run on some event, such as when a user clicks somewhere, then you will
place that script in the head as follows –
<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
If you need a script to run as the page loads so that the script generates content in the page, then the script
goes in the <body> portion of the document. In this case, you would not have any function defined using
JavaScript. Take a look at the following code.
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-- -->
</script>
<p>This is web page body </p>
</body>
</html> #This code will produce the following results −
JavaScript in <body> and <head> Sections
You can put your JavaScript code in <head> and <body> section altogether as follows −
<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>
This code will produce the following result −
JavaScript in External File
As you begin to work more extensively with JavaScript, you will be likely to find that there are cases where
you are reusing identical JavaScript code on multiple pages of a site.
You are not restricted to be maintaining identical code in multiple HTML files. The script tag provides a
mechanism to allow you to store JavaScript in an external file and then include it into your HTML files.
Here is an example to show how you can include an external JavaScript file in your HTML code using script
tag and its src attribute.
<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
.......
</body>
</html>
To use JavaScript from an external file source, you need to write all your JavaScript source code in a simple
text file with the extension ".js" and then include that file as shown above.
For example, you can keep the following content in filename.js file and then you can use sayHello function in
your HTML file after including the filename.js file.
function sayHello() {
alert("Hello World")
}
JAVASCRIPT OUTPUT
JavaScript does NOT have any built-in print or display functions.
JavaScript Display Possibilities
JavaScript can "display" data in different ways:
• Writing into an alert box, using window.alert().
• Writing into the HTML output using document.write().
• Writing into an HTML element, using innerHTML.
• Writing into the browser console, using console.log().
Using window.alert()
You can use an alert box to display data:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body></html>
Using document.write()
For testing purposes, it is convenient to use document.write():
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Using document.write() after an HTML document is fully loaded, will delete all existing HTML:
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<button onclick="document.write(5 + 6)">Try it</button>


</body>
</html>
Using innerHTML
To access an HTML element, JavaScript can use the document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines the HTML content:
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My First Paragraph</p>
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html>

Using console.log()
In your browser, you can use the console.log() method to display data.
Activate the browser console with F12, and select "Console" in the menu.
Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
console.log(5 + 6);
</script>

</body>
</html>
SYNTAX OF JAVASCRIPT
JavaScript syntax is the set of rules, how JavaScript programs are constructed.
A computer program is a list of "instructions" to be "executed" by the computer.
In a programming language, these program instructions are called statements. JavaScript is a programming
language.
JavaScript statements are separated by semicolons.
var x = 5;
var y = 6;
var z = x + y;

Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.

Values
The JavaScript syntax defines two types of values: Fixed values and variable values.
Fixed values are called literals. Variable values are called variables.

Variables
In a programming language, variables are used to store data values.
JavaScript uses the var keyword to define variables.
An equal sign is used to assign values to variables.
In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
var x;
x = 6;

Operators
JavaScript uses an assignment operator ( = ) to assign values to variables:
var x = 5;
var y = 6;
JavaScript uses arithmetic operators ( + - * / ) to compute values:
(5 + 6) * 10
Expressions
An expression is a combination of values, variables, and operators, which computes to a value.
The computation is called an evaluation.
For example, 5 * 10 evaluates to 50:
5 * 10
Expressions can also contain variable values:
x * 10
The values can be of various types, such as numbers and strings.
For example, "John" + " " + "Doe", evaluates to "John Doe":
"John" + " " + "Doe"
Keywords
Keywords are used to identify actions to be performed. The var keyword tells the browser to create a new
variable:
var x = 5 + 6;
var y = x * 10;
Comments in JavaScript
JavaScript supports both C-style and C++-style comments, Thus −
• Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.
• Any text between the characters /* and */ is treated as a comment. This may span multiple lines.
• JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-
line comment, just as it does the // comment.
• The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as // - >
Identifiers
Identifiers are names.
In JavaScript, identifiers are used to name variables (and keywords, and functions, and labels).
The rules for legal names are much the same in most programming languages.
In JavaScript, the first character must be a letter, an underscore (_), or a dollar sign ($).
Subsequent characters may be letters, digits, underscores, or dollar signs.
FUNCTIONS
• A function is a block of code designed to perform a particular task.
• 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.
• A JavaScript function is executed when "something" invokes it (calls it).
Syntax
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
function name(parameter1, parameter2, parameter3) {
code to be executed
}
Function parameters are the names listed in the function definition. Function arguments are the real values
received by the function when it is invoked. Inside the function, the arguments are used as local variables.
function myFunction(p1, p2) {
return p1 * p2; // The function returns the product of p1 and p2
}
Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:
• When an event occurs (when a user clicks a button)
• When it is invoked (called) from JavaScript code
• Automatically (self invoked)
<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('Zara', 7)" value="Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
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.
<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>
Nested Functions
Function inside another function is known as Nested Functions.
<html>
<head>
<script type="text/javascript">
<!--
function hypotenuse(a, b) {
function square(x) { return x*x; }
return Math.sqrt(square(a) + square(b));
}
function secondFunction(){
var result;
result = hypotenuse(1,2);
document.write ( result );
}
//-->
</script>
</head>
<body>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
</body>
</html>

Function Constructors
The function statement is not the only way to define a new function; you can define your function
dynamically using Function() constructor along with the new operator.
Note − Constructor is a terminology from Object Oriented Programming. You may not feel comfortable for
the first time, which is OK.
Syntax
Following is the syntax to create a function using Function( ) constructor along with the new operator.
<script type="text/javascript">
var variablename = new Function(Arg1, Arg2..., "Function Body");
</script>
The Function() constructor expects any number of string arguments. The last argument is the body of the
function – it can contain arbitrary JavaScript statements, separated from each other by semicolons.
Notice that the Function() constructor is not passed any argument that specifies a name for the function it
creates. The unnamed functions created with the Function() constructor are called anonymous functions.
<html>
<head>
<script type="text/javascript">
<!--
var func = new Function("x", "y", "return x*y;");
function secondFunction(){
var result;
result = func(10,20);
document.write ( result );
}
//-->
</script>
</head>
<body>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form> </body> </html>
Function literals
Function literals which is another new way of defining functions. A function literal is an expression that
defines an unnamed function.
Syntax
The syntax for a function literal is much like a function statement, except that it is used as an expression
rather than a statement and no function name is required.
<script type="text/javascript">
var variablename = function(Argument List){
Function Body
};
</script>
Syntactically, you can specify a function name while creating a literal function as follows.
<script type="text/javascript">
var variablename = function FunctionName(Argument List){
Function Body
};
</script>
But this name does not have any significance, so it is not worthwhile.
<html>
<head>
<script type="text/javascript">
var func = function(x,y){ return x*y };
function secondFunction(){
var result;
result = func(10,20);
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>
</body></html>

OBJECTS
Objects are composed of attributes. If an attribute contains a function, it is considered to be a method of
the object, otherwise the attribute is considered a property.
In real life, a car is an object.
A car has properties like weight and color, and methods like start and stop:
All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different times.
var car = "Fiat";
Objects are variables too. But objects can contain many values.
var car = {type:"Fiat", model:500, color:"white"};
Properties
The name:values pairs (in JavaScript objects) are called properties.
var person = {firstName:"Kalpana", lastName:"Vijayaraghavan", age:32};
Example
<!DOCTYPE html><html>
<body>
<p id="demo"></p>
<script>
var person = {firstName:"Kalpana", lastName:"Vijayaraghavan", age:32};
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>
</body></html>

Accessing Object Properties


You can access object properties in two ways:
objectName.propertyName
or
objectName[propertyName]
<!DOCTYPE html>
<html><body>
OUTPUT
<p id="demo1"></p>
<p id="demo"></p> Kalpana Sri

<script> Kalpana Sri


var person = {
firstName: "Kalpana",
lastName : "Sri",
id : 5566
};
document.getElementById("demo").innerHTML = person.firstName + " " + person.lastName;
document.getElementById("demo1").innerHTML = person["firstName"] + " " + person.lastName;
</script>
</body></html>
Methods
• Methods are actions that can be performed on objects.
• Methods are stored in properties as function definitions.
• 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.

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 newoperator 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 theObject() 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 = "C++"; // Assign properties to the object
OUTPUT:
book.author = "Ira Pohl";
Book name is : C++
</script>
</head> Book author is : Ira Pohl
<body>
<script type="text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body> </html>

Example 2:
<html> <head>
<title>User-defined objects</title> OUTPUT:

<script type="text/javascript"> Book name is : C++


function book(title, author){ Book author is : Ira Pohl
this.title = title;
this.author = author;
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("C++", "Ira Pohl");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
</script>
</body></html>
Defining Methods for an Object
<html>
<head>
<title>User-defined objects</title>

<script type="text/javascript">
// Define a function which will work as a method
function addPrice(amount){
this.price = amount;
OUTPUT:
}
function book(title, author){ Book name is : C++

this.title = title; Book author is : Ira Pohl


this.author = author;
Book price is : 100
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("C++", "Ira Pohl");
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>");
</script> </body> </html>

NUMBER OBJECT
The Number object represents numerical date, either integers or floating-point numbers. In general, you
do not need to worry about Number objects because the browser automatically converts number literals
to instances of the number class.
Syntax
The syntax for creating a number object is as follows −
var val = new Number(number);
In the place of number, if you provide any non-number argument, then the argument cannot be
converted into a number, it returns NaN (Not-a-Number).
Converting Variables to Numbers
There are 3 JavaScript functions that can be used to convert variables to numbers:
• The Number() method
• The parseInt() method
• The parseFloat() method
These methods are not number methods, but global JavaScript methods.

The Number() Method - can be used to convert JavaScript variables to numbers:


x = true;
Number(x); // returns 1
x = false;
Number(x); // returns 0
x = new Date();
Number(x); // returns 1404568027739
x = "10"
Number(x); // returns 10
x = "10 20"
Number(x); // returns NaN

The parseInt() Method - parses a string and returns a whole number. Spaces are allowed. Only the
first number is returned:
parseInt("10"); // returns 10
parseInt("10.33"); // returns 10
parseInt("10 20 30"); // returns 10
parseInt("10 years"); // returns 10
parseInt("years 10"); // returns NaN

The parseFloat() Method - parses a string and returns a number. Spaces are allowed. Only the first
number is returned:
parseFloat("10"); // returns 10
parseFloat("10.33"); // returns 10.33
parseFloat("10 20 30"); // returns 10
parseFloat("10 years"); // returns 10
parseFloat("years 10"); // returns NaN
The valueOf() Method - returns a number as a number.
var x = 123;
x.valueOf(); // returns 123 from variable x
(123).valueOf(); // returns 123 from literal 123
(100 + 23).valueOf(); // returns 123 from expression 100 + 23
Global Methods
JavaScript global functions can be used on all JavaScript data types.

Global Methods
JavaScript global functions can be used on all JavaScript data types.
These are the most relevant methods, when working with numbers:

Method Description

Number() Returns a number, converted from its argument.

parseFloat() Parses its argument and returns a floating point


number

parseInt() Parses its argument and returns an integer

Number Methods
JavaScript number methods are methods that can be used on numbers:

Method Description

toString() Returns a number as a string

toExponential() Returns a string, with a number rounded and written using


exponential notation.

toFixed() Returns a string, with a number rounded and written with a


specified number of decimals.

toPrecision() Returns a string, with a number written with a specified length

valueOf() Returns a number as a number


<!DOCTYPE html><html>
<body>
<button onclick="myFunction()">Demo</button>
<p id="demo"></p>
<script>
function myFunction() {
var x1 = true;
var x2 = false;
var x3 = new Date();
var x4 = "999";
var x5 = "999 888";
var x6 = parseInt("40 years");
var x7 = parseFloat("36.00");
var x8 = isNaN("x6");
var n =
Number(x1) + "<br>" +
Number(x2) + "<br>" +
Number(x3) + "<br>" +
Number(x4) + "<br>" +
Number(x5)+ "<br>"+
x6 +"<br>" + x7 + "<br>" + x8 + "<br>" + String(x3);
document.getElementById("demo").innerHTML = n;
}
</script>
</body></html>

BOOLEAN OBJECT
The Boolean object represents two values, either "true" or "false". If value parameter is omitted or is 0, -
0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.
Syntax
Use the following syntax to create a boolean object.
var val = new Boolean(value);
Method Description

toSource() Returns a string containing the source of the Boolean object; you
can use this string to create an equivalent object.

toString() Returns a string of either "true" or "false" depending upon the


value of the object.

valueOf() Returns the primitive value of the Boolean object.

<!DOCTYPE html>
<html><body>
<button onclick="myFunction()">Check</button>
<p id="demo"></p>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML = Boolean(10 > 9);
}
</script>
</body></html>

ARRAY OBJECT
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
var fruits = new Array( "apple", "orange", "mango" );
OR
var fruits = [ "apple", "orange", "mango" ]; //easiest method - literal
You will use ordinal numbers to access and to set values inside an array as follows.
fruits[0] is the first element
fruits[1] is the second element
fruits[2] is the third element
Method Description

concat() Joins two or more arrays, and returns a copy of the joined arrays

indexOf() Search the array for an element and returns its position

join() Joins all elements of an array into a string

lastIndexOf() Search the array for an element, starting at the end, and returns
its position

pop() Removes the last element of an array, and returns that element

push() Adds new elements to the end of an array, and returns the new
length

reverse() Reverses the order of the elements in an array

shift() Removes the first element of an array, and returns that element

slice() Selects a part of an array, and returns the new array

sort() Sorts the elements of an array

splice() Adds/Removes elements from an array

toString() Converts an array to a string, and returns the result

unshift() Adds new elements to the beginning of an array, and returns the
new length

valueOf() Returns the primitive value of an array

Example:
<!DOCTYPE html><html>
<body>
<button onclick="myNumber()">Sorting of Numbers</button>
<p id="demo"></p>
<p id="demo1"></p>
<button onclick="myFruits()">Sorting of Alphabets</button>
<p id="demo2"></p>
<button onclick="myList()">Listing Fruits</button>
<p id="demo3"></p>
<script>
function myFruits() {
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); //to add an element to the array
fruits[fruits.length] = "Pomegranate"
fruits[6]="Grapes"
document.getElementById("demo2").innerHTML = fruits;
fruits.sort();
fruits.reverse();
document.getElementById("demo2").innerHTML = fruits;
}
function myNumber() {
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
document.getElementById("demo").innerHTML = points;
points.sort(function(a, b){return b-a});
document.getElementById("demo1").innerHTML = points;
}
function myList()
{
var index;
var text = "<ul>";
var fruits = ["Banana", "Orange", "Apple", "Mango"];
for (index = 0; index < fruits.length; index++) {
text += "<li>" + fruits[index] + "</li>";
}
text += "</ul>";
document.getElementById("demo3").innerHTML = text;
}
</script>
</body>
</html>
<script>
function myFruits() {
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); //to add an element to the array
fruits[fruits.length] = "Pomegranate"
fruits[6]="Grapes"
document.getElementById("demo2").innerHTML = fruits;
fruits.sort();
fruits.reverse();
document.getElementById("demo2").innerHTML = fruits;
}
function myNumber() {
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
document.getElementById("demo").innerHTML = points;
points.sort(function(a, b){return b-a});
document.getElementById("demo1").innerHTML = points;
}
function myList()
{
var index;
var text = "<ul>";
var fruits = ["Banana", "Orange", "Apple", "Mango"];
for (index = 0; index < fruits.length; index++) {
text += "<li>" + fruits[index] + "</li>";
}
text += "</ul>";
document.getElementById("demo3").innerHTML = text;
}
</script>
</body>
</html>
DATE OBJECT

Method Description

getDate() Returns the day of the month (from 1-31)

getDay() Returns the day of the week (from 0-6)

getFullYear() Returns the year (four digits)

getHours() Returns the hour (from 0-23)

getMillisecon Returns the milliseconds (from 0-999)


ds()

getMinutes() Returns the minutes (from 0-59)

getMonth() Returns the month (from 0-11)

getSeconds() Returns the seconds (from 0-59)

getTime() Returns the number of milliseconds since midnight Jan 1, 1970

getTimezone Returns the time difference between UTC time and local time, in
Offset() minutes

getUTCDate() Returns the day of the month, according to universal time (from 1-31)

getUTCDay() Returns the day of the week, according to universal time (from 0-6)

parse() Parses a date string and returns the number of milliseconds since
January 1, 1970
DATE OBJECT

Method Description

setDate() Sets the day of the month of a date object

setFullYear() Sets the year (four digits) of a date object

setHours() Sets the hour of a date object

setMilliseconds Sets the milliseconds of a date object


()

setMinutes() Set the minutes of a date object

setMonth() Sets the month of a date object

setSeconds() Sets the seconds of a date object

setTime() Sets a date to a specified number of milliseconds after/before


January 1, 1970

setUTCDate() Sets the day of the month of a date object, according to universal
time

toDateString() Converts the date portion of a Date object into a readable string

toString() Converts a Date object to a string

UTC() Returns the number of milliseconds in a date since midnight of


January 1, 1970, according to UTC time

valueOf() Returns the primitive value of a Date object

<<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Print Date</button>
<script>
function myFunction() {
var d = new Date();
var m = d.getMonth();
var day = d.getDay();
document.write(d + "<br> ");
document.write("The Day is :"+ day + "<br>");
document.write(d.getHours()+":" +d.getMinutes()+":"+d.getSeconds()+"<br>");
document.write(d.getDate() +"/" +d.getMonth()+"/"+d.getFullYear()+"<br>");
d.setDate(23);
document.write(d.getDate() +"/" +d.getMonth()+"/"+d.getFullYear()+"<br>");
}
</script></body></html>

MATH OBJECT
The Math object allows you to perform mathematical tasks on numbers.
Constants
Math.E // returns Euler's number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E
Method Description

abs(x) Returns the absolute value of x

acos(x) Returns the arccosine of x, in radians

asin(x) Returns the arcsine of x, in radians

atan(x) Returns the arc tangent of x as a numeric value between -


PI/2 and PI/2 radians

atan2(y,x) Returns the arctangent of the quotient of its arguments

ceil(x) Returns x, rounded upwards to the nearest integer

cos(x) Returns the cosine of x (x is in radians)

exp(x) Returns the value of Ex

floor(x) Returns x, rounded downwards to the nearest integer

log(x) Returns the natural logarithm (base E) of x

max(x,y,z,...,n) Returns the number with the highest value

min(x,y,z,...,n) Returns the number with the lowest value

pow(x,y) Returns the value of x to the power of y

random() Returns a random number between 0 and 1

round(x) Rounds x to the nearest integer

sin(x) Returns the sine of x (x is in radians)

sqrt(x) Returns the square root of x

tan(x) Returns the tangent of an angle


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Math Object</button>
<script>
function myFunction() {
document.write(Math.min(0, 150, 30, 20, -8, -200));
document.write("<br>");
document.write(Math.max(0, 150, 30, 20, -8, -200));
document.write("<br>");
document.write(Math.random());
document.write("<br>");
document.write(Math.round(4.7888));
document.write("<br>");
document.write(Math.SQRT2);
document.write("<br>");
document.write(Math.SQRT1_2);
document.write("<br>");
}
</script>
</body>
</html>

STRING OBJECTS
A JavaScript string simply stores a series of characters like "John Doe".
A string can be any text inside quotes. You can use single or double quotes:
var answer = "It's alright";
var answer = "He is called 'Johnny'";
var answer = 'He is called "Johnny"';
String Length
The length of a string is found in the built in property length:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
Special Characters
Because strings must be written within quotes, JavaScript will misunderstand this string:
var y = "We are the so-called "Vikings" from the north."
The string will be chopped to "We are the so-called ".
The solution to avoid this problem, is to use the \ escape character.
The backslash escape character turns special characters into string characters:
var x = 'It\'s alright';
var y = "We are the so-called \"Vikings\" from the north."
The escape character (\) can also be used to insert other special characters in a string.
This is the list of special characters that can be added to a text string with the backslash sign:

Code Outputs

\' single quote

\" double quote

\\ backslash

\n new line

\r carriage return

\t tab

\b backspace

\f form feed
String Methods

Method Description

charAt() Returns the character at the specified index (position)

charCodeAt() Returns the Unicode of the character at the specified index

concat() Joins two or more strings, and returns a copy of the joined
strings

fromCharCode() Converts Unicode values to characters

indexOf() Returns the position of the first found occurrence of a specified


value in a string

lastIndexOf() Returns the position of the last found occurrence of a specified


value in a string

localeCompare() Compares two strings in the current locale

match() Searches a string for a match against a regular expression, and


returns matches

replace() Searches a string for a value and returns a new string with the
value replaced

search() Searches a string for a value and returns the position of the
match

slice() Extracts a part of a string and returns a new string

split() Splits a string into an array of substrings

substr() Extracts a part of a string from a start position through a


number of characters

substring() Extracts a part of a string between two specified positions

toLocaleLowerCase() Converts a string to lowercase letters, according to the host's


locale

toLocaleUpperCase() Converts a string to uppercase letters, according to the host's


locale

toLowerCase() Converts a string to lowercase letters

toString() Returns the value of a String object

toUpperCase() Converts a string to uppercase letters

trim() Removes whitespace from both ends of a string

valueOf() Returns the primitive value of a String object


<html>
<head>
<title>Strings</title>
</head>
<body>
<script type="text/javascript">
var str = "Apples are round, and apples are juicy.";
var splitted = str.split(" ", 3);
var y = "We are the so-called \"Vikings\" from the north.";
document.write( splitted );
document.write("<br>");
document.write(y);
document.write("<br>");
document.write(y.toUpperCase());
document.write("<br>");
document.write(y.search('V'));
document.write("<br>");
document.write(y.slice(22,-2));
document.write("<br>");
document.write(y.substring(22,29));
</script>
</body>
</html>
REGULAR EXPRESSIONS
• A regular expression is a sequence of characters that forms a search pattern.
• When you search for data in a text, you can use this search pattern to describe what you
are searching for.
• A regular expression can be a single character, or a more complicated pattern.
• Regular expressions can be used to perform all types of text search and text replace
operations.
Syntax
A regular expression could be defined with the RegExp () constructor, as follows –
var pattern = /pattern/attibutes;
OR
var pattern = new RegExp(pattern, attributes);
Here is the description of the parameters –
• pattern − A string that specifies the pattern of the regular expression or another regular
expression.
• attributes − An optional string containing any of the "g", "i", and "m" attributes that specify
global, case-insensitive, and multiline matches, respectively.
Brackets
Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to
find a range of characters.

Expression Description

[...] Any one character between the brackets.

[^...] Any one character not between the brackets.

[0-9] It matches any decimal digit from 0 through 9.

[a-z] It matches any character from lowercase a through lowercase z.

[A-Z] It matches any character from uppercase A through uppercase Z.

[a-Z] It matches any character from lowercase a through uppercase Z.

The ranges shown above are general; you could also use the range [0-3] to match any decimal digit
ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v.
Quantifiers
The frequency or position of bracketed character sequences and single characters can be denoted by a
special character. Each special character has a specific connotation. The +, *, ?, and $ flags all follow a
character sequence.

Expressio Description
n

p+ It matches any string containing at least one p.

p* It matches any string containing zero or more p's.

p? It matches any string containing one or more p's.

p{N} It matches any string containing a sequence of N p's

p{2,3} It matches any string containing a sequence of two or three p's.

p{2, } It matches any string containing a sequence of at least two p's.

p$ It matches any string with p at the end of it.

^p It matches any string with p at the beginning of it.

Following examples explain more about matching characters.

Expression Description

[^a-zA-Z] It matches any string not containing any of the characters ranging
from athrough z and A through Z.

p.p It matches any string containing p, followed by any character, in turn


followed by another p.

^.{2}$ It matches any string containing exactly two characters.

<b>(.*)</b> It matches any string enclosed within <b> and </b>.

p(hp)* It matches any string containing a p followed by zero or more


instances of the sequence hp.
Literal characters
Character Description

Alphanumeric Itself

\0 The NUL character (\u0000)

\t Tab (\u0009)

\n Newline (\u000A)

\v Vertical tab (\u000B)

\f Form feed (\u000C)

\r Carriage return (\u000D)

\xnn The Latin character specified by the hexadecimal number nn; for example,
\x0A is the same as \n

\uxxxx The Unicode character specified by the hexadecimal number xxxx; for
example, \u0009 is the same as \t

\cX The control character ^X; for example, \cJ is equivalent to the newline
character \n

Metacharacters
A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the
combination a special meaning. For instance, you can search for a large sum of money using the '\d'
metacharacter:/([\d]+)000/, Here \d will search for any string of numerical character. The following table
lists a set of metacharacters which can be used in PERL Style Regular Expressions.

Character Description

. a single character

\s a whitespace character (space, tab, newline)

\S non-whitespace character

\d a digit (0-9)

\D a non-digit

\w a word character (a-z, A-Z, 0-9, _)

\W a non-word character

[\b] a literal backspace (special case).

[aeiou] matches a single character in the given set

[^aeiou] matches a single character outside the given set

(foo|bar|baz) matches any of the alternatives specified


Modifiers
Several modifiers are available that can simplify the way you work with regexps, like case sensitivity,
searching in multiple lines, etc.

Modifier Description

i Perform case-insensitive matching.

M Specifies that if the string has newline or carriage return characters,


the ^ and $ operators will now match against a newline boundary,
instead of a string boundary

G Performs a global match that is, find all matches rather than stopping
after the first match.

Search & Replace


In JavaScript, regular expressions are often used with the two string methods: search() and replace().
The search() method uses an expression to search for a match, and returns the position of the match.
The replace() method returns a modified string where the pattern is replaced.
Using String search( ) With a Regular Expression
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Search</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Velammal Institute of Technology";
var n = str.search(/Institute/i);
document.getElementById("demo").innerHTML = n;
}
</script>
</body></html>
Using String replace( ) With a Regular Expression
<!DOCTYPE html>
<html>
<body>
<p>Replace "velammal" with "Vellore" in the paragraph below:</p>
<button onclick="myFunction()">Replace</button>

<p id="demo">Please visit Velammal Institute of Technology!</p>


<script>
function myFunction()
{
var str = document.getElementById("demo").innerHTML;
var txt = str.replace(/velammal/i,"Vellore");
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>

FORM VALIDATION USING JAVASCRIPT REGULAR EXPRESSIONS

Usage Pattern
1.Username [Min 8 Chars and /^[a-z0-9]{8,}/i
alpha numeric characters)
2. Email ID /^[a-z0-9._-]+@[a-z]+.[a-z.]{2,5}$/i
3. Date of Birth /^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$/i
4. Mobile Number /^([+0-9]{1,3})?([0-9]{10,11})$/i
5. Web Site URL /^[http://]+[www]?.[0-9a-z_.]+.[a-z.]{2,5}$/i
6. Pincode /^[0-9]{6}$/i
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<title>Registration Form</title>

<!-- Meta Tags -->


<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<!-- CSS -->


<link rel="stylesheet" href="css/structure.css" type="text/css" />
<link rel="stylesheet" href="css/form.css" type="text/css" />

<!-- JavaScript -->


<script type="text/javascript" src="9lessons.js"></script>
<script type="text/javascript">
var ck_name = /^[A-Za-z0-9 ]{3,20}$/;
var ck_email = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
var ck_username = /^[A-Za-z0-9_]{1,20}$/;
var ck_password = /^[A-Za-z0-9!@#$%^&*()_]{6,20}$/;

function validate(form){
var name = form.name.value;
var email = form.email.value;
var username = form.username.value;
var password = form.password.value;
var gender = form.gender.value;
var errors = [];

if (!ck_name.test(name)) {
errors[errors.length] = "You valid Name .";
}
if (!ck_email.test(email)) {
errors[errors.length] = "You must enter a valid email address.";
}
if (!ck_username.test(username)) {
errors[errors.length] = "You valid UserName no special char .";
}

if (!ck_password.test(password)) {
errors[errors.length] = "You must enter a valid Password min 6 char.";
}
if (gender==0) {
errors[errors.length] = "Select Gender"; }
if (errors.length > 0) {
reportErrors(errors);
return false;
}
return true;
}

function reportErrors(errors){
var msg = "Please Enter Valide Data...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>
</head>
<body id="public">
<div style="height:30px"></div>
<div id="container">
<div style="height:30px"></div>
<form autocomplete="off"
enctype="multipart/form-data" method="post" action="thanks.html" onSubmit="return
validate(this);" name="form">

<div class="info" style="padding-left:20px">


<h2>Registration Form</h2>
<ul>
<li id="foli1" class=" ">
<label class="desc" id="title1" for="Field1">Full Name</label>
<div><input id="name" name="name" type="text" class="field text medium"
value="" maxlength="255" tabindex="1"/></div>
</li>
<li id="foli2" class=" ">
<label class="desc" id="title2" for="Field2">Email</label>
<div> <input id="email" name="email" type="text" class="field text medium"
value="" maxlength="255" tabindex="2"/></div> </li>
<li id="foli3" class=" ">
<label class="desc" id="title3" for="Field3">User-ID</label>
<div><input id="username" name="username" type="text" class="field text medium" value=""
maxlength="255"tabindex="3"/></div> </li>
<li id="foli4" class=" ">
<label class="desc" id="title4" for="Field4">Password</label>
<div>
<input id="password" name="password" type="password" class="field text medium" value=""
maxlength="255" tabindex="4"/></div> </li>
<li id="foli6" class=" ">
<label class="desc" id="title6" for="Field6">Gender</label>
<div>
<select id="gender" name="gender" class="field select medium" tabindex="5">
<option value="0">Gender</option><option value="1">Male</option><option
value="2">Female</option></select> </div> </li>
<li id="foli15" class=" "></li>
<li class="buttons">
<input type="submit" value="Submit" style=" background:#0060a1; color:#FFFFFF; font-size:14px;
border:1px solid #0060a1"/> </li>
</ul></form>
<div style="height:20px"></div>
</div><!--container-->
</body></html>
</ul>
</form>
<div style="height:20px"></div>
</div><!--container-->
</body></html>
DOCUMENT OBJECT MODEL (THE DOM MODEL)
• When a web page is loaded, the browser creates a Document Object Model of the page.
• Every web page resides inside a browser window which can be considered as an object.
• A Document object represents the HTML document that is displayed in that window. The Document
object has various properties that refer to other objects which allow access to and modification of
document content.
• The way a document content is accessed and modified is called the Document Object Model, or DOM.
The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects
in a Web document.
• The HTML DOM model is constructed as a tree of Objects:

With the object model, JavaScript gets all the power it needs to create dynamic HTML:
• JavaScript can change all the HTML elements in the page
• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page
What is the DOM?
The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents:
"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."
The W3C DOM standard is separated into 3 different parts:
• Core DOM - standard model for all document types
• XML DOM - standard model for XML documents
• HTML DOM - standard model for HTML documents

What is the HTML DOM?


The HTML DOM is a standard object model and programming interface for HTML. It defines:
• The HTML elements as objects
• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements
In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.
HTML DOM methods are actions you can perform (on HTML Elements)
HTML DOM properties are values (of HTML Elements) that you can set or change

The DOM Programming Interface


The HTML DOM can be accessed with JavaScript (and with other programming languages).
In the DOM, all HTML elements are defined as objects.
The programming interface is the properties and methods of each object.
A property is a value that you can get or set (like changing the content of an HTML element).
A method is an action you can do (like add or deleting an HTML element).

Example
The following example changes the content (the innerHTML) of the <p> element with id="demo":
Example
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
In the example above, getElementById is a method, while innerHTML is a property.
The getElementById Method
The most common way to access an HTML element is to use the id of the element.
In the example above the getElementById method used id="demo" to find the element.
The innerHTML Property
The easiest way to get the content of an element is by using the innerHTML property.
The innerHTML property is useful for getting or replacing the content of HTML elements.
The HTML DOM Document
In the HTML DOM object model, the document object represents your web page.
The document object is the owner of all other objects in your web page.
If you want to access objects in an HTML page, you always start with accessing the document object.
Finding HTML Elements

Method Description

document.getElementById() Find an element by element id

document.getElementsByTagName() Find elements by tag name

document.getElementsByClassName() Find elements by class name

Changing HTML Elements

Method Description

element.innerHTML= Change the inner HTML of an element

element.attribute= Change the attribute of an HTML element

element.setAttribute(attribute,va Change the attribute of an HTML element


lue)

element.style.property= Change the style of an HTML element

Adding Events Handlers

Method Description

document.getElementById(id).onclick=functio Adding event handler code to an


n(){code} onclick event
Adding and Deleting Elements

Method Description

document.createElement() Create an HTML element

document.removeChild() Remove an HTML element

document.appendChild() Add an HTML element

document.replaceChild() Replace an HTML element

document.write(text) Write into the HTML output stream

Finding HTML Objects


The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections, and properties. These are
still valid in HTML5.
Later, in HTML DOM Level 3, more objects, collections, and properties were added.

Property Description DOM

document.anchors Returns all <a> elements that have a 1


name attribute

document.applets Returns all <applet> 1


elements (Deprecated in HTML5)

document.baseURI Returns the absolute base URI of the 3


document

document.body Returns the <body> element 1

document.cookie Returns the document's cookie 1

document.doctype Returns the document's doctype 3

document.documentElement Returns the <html> element 3

document.documentMode Returns the mode used by the browser 3

document.documentURI Returns the URI of the document 3

document.domain Returns the domain name of the 1


document server

document.domConfig Obsolete. Returns the DOM configuration 3

document.embeds Returns all <embed> elements 3


Finding HTML Objects

Property Description DOM

document.forms Returns all <form> elements 1

document.head Returns the <head> element 3

document.images Returns all <img> elements 1

document.implementation Returns the DOM implementation 3

document.inputEncoding Returns the document's encoding 3


(character set)

document.lastModified Returns the date and time the document 3


was updated

document.links Returns all <area> and <a> elements 1


that have a href attribute

document.readyState Returns the (loading) status of the 3


document

document.referrer Returns the URI of the referrer (the 1


linking document)

document.scripts Returns all <script> elements 3

document.strictErrorCheckin Returns if error checking is enforced 3


g

document.title Returns the <title> element 1

document.URL Returns the complete URL of the 1


document

EVENT HANDLING
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.
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.
Mouse Events
1)onmouseover/onmouseout
• When the mouse passes over an element
• onmouseover - JavaScript code is called when the mouse is placed over a specific link or an object
or area from outside that object or area
• onmouseout - JavaScript code is called when the mouse leaves a specific link or an object or area
from outside that object or area.
<!DOCTYPE html>
<html>
<head>
<script>
function bigImg(x) {
x.style.height = "64px";
x.style.width = "64px";
}
function normalImg(x) {
x.style.height = "32px";
x.style.width = "32px";
}</script></head><body>
<img onmouseover="bigImg(this)" onmouseout="normalImg(this)" border="0" src="smiley.gif"
alt="Smiley" width="32" height="32">
</body></html>

.Output:
2) onmousedown/onmouseup - When pressing/releasing a mouse button
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(elmnt, clr) {
elmnt.style.color = clr;
}
</script></head><body>
<p onmousedown="myFunction(this,'red')" onmouseup="myFunction(this,'green')">
Click the text to change the color.
</p></body></html>
Output:

3) onmousemove/onmouseout - When moving the mouse pointer over/out of an image


<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(e) {
x = e.clientX;
y = e.clientY;
coor = "Coordinates: (" + x + "," + y + ")";
document.getElementById("demo").innerHTML = coor
}
function clearCoor() {
document.getElementById("demo").innerHTML = "";
}
</script>
</head>
<body style="margin:0px;">
<div id="coordiv" style="width:199px;height:99px;border:1px solid" onmousemove="myFunction(event)"
onmouseout="clearCoor()"></div>
<p>Mouse over the rectangle above, and get the coordinates of your mouse pointer.</p>
<p id="demo"></p>
</body></html>
Output:

Click Events
• onClick
• ondblClick
1) 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.
In an onClick event handler, JavaScript function is called when an object in a button (regular, radio, reset
and submit) is clicked, a link is pushed, a checkbox is checked or an image map area is selected. Except for
the regular button and the area, the onClick event handler can return false to cancel the action. For
example:
<INPUT TYPE="submit" NAME="mysubmit" VALUE="Submit" onClick="return confirm(`Are you sure you
want to submit the form?')">
Example
<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>

ondblclick 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.
Example
<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" ondblclick="sayHello()" value="Say Hello" />
</form> </body></html>
Input Events
Onblur
• Execute a JavaScript when a user leaves an input field:
• The onblur event occurs when an object loses focus.
• The onblur event is most often used with form validation code (e.g. when the user leaves a
form field).
Tip: The onblur event is the opposite of the onfocus event.
Tip: The onblur event is similar to the onfocusout event. The main difference is that the onblur event does
not bubble. Therefore, if you want to find out whether an element or its child loses focus, you could use the
onfocusout event. However, you can achieve this by using the optional useCapture parameter of the
addEventListener() method for the onblur event.
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" onblur="myFunction()">
</body></html>
Output:

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.
<!DOCTYPE html>
<html>
<body>
<form action="demo_form.php" onsubmit="myFunction()">
Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
function myFunction() {
alert("The form was submitted");
}
</script></body></html>

Output

Onchange() Event
• When the user selects the drop down value
• The onChange event handler executes JavaScript code when input focus exits the field
after the user modifies its text.
<!DOCTYPE html>
<html>
<head>
<script>
function preferedBrowser() {
prefer = document.forms[0].browsers.value;
alert("You prefer browsing internet with " + prefer);
}
</script>
</head>
<body>
<form>
Choose which browser you prefer:
<select id="browsers" onchange="preferedBrowser()">
<option value="Chrome">Chrome</option>
<option value="Internet Explorer">Internet Explorer</option>
<option value="Firefox">Firefox</option>
</select>
</form></body></html>
Output:

OnFocus() Event
• When an input field gets focused
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(x) {
x.style.background = "yellow";
}
</script>
</head>
<body>
Enter your name: <input type="text" onfocus="myFunction(this)">
</body>
</html>
Output:
Load Events
Onload() Event
• When the image has been loaded.
• An onLoad event occurs when a window or image finishes loading. For windows, this event
handler is specified in the BODY attribute of the window. In an image, the event handler will
execute handler text when the image is loaded. For example:
<IMG NAME="myimage" SRC="http://rhoque.com/ad_rh.jpg" onLoad="alert('You loaded myimage')">
<!DOCTYPE html>
<html>
<head>
<script>
function loadImage() {
alert("Image is loaded");
}
</script>
</head>
<body>
<img src="w3javascript.gif" onload="loadImage()" width="100" height="132">
</body>
</html>

Output:
Onunload() Event
•When the browser closes the document.
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
alert("Thank you for visiting W3Schools!");
}
</script>
</head>
<body onunload="myFunction()">
<h1>Welcome to my Home Page</h1>
<p>Close this window or press F5 to reload the page.</p>
</body>
</html>

Output:

A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.
To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:
onclick = Javascript
Examples of HTML events:
• When a user clicks the mouse
• When a web page has loaded
• When an image has been loaded
• When the mouse moves over an element
• When an input field is changed
• When an HTML form is submitted
• When a user strokes a key
In this example, the content of the <h1> element is changed when a user clicks on it:
<!DOCTYPE html>
<html>
<body>
<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>
</body>
</html>
In this example, a function is called from the event handler:
<!DOCTYPE html>
<html>
<body>
<h1 onclick="changeText(this)">Click on this text!</h1>
<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>
</body>
</html>

Assign Events Using the HTML DOM


The HTML DOM allows you to assign events to HTML elements using JavaScript:
Assign an onclick event to a button element:
<script>
document.getElementById("myBtn").onclick = displayDate;
</script>
In the example above, a function named displayDate is assigned to an HTML element with the
id="myBtn".
The function will be executed when the button is clicked.

The onload and onunload Events


The onload and onunload events are triggered when the user enters or leaves the page.
The onload event can be used to check the visitor's browser type and browser version, and load the proper
version of the web page based on the information.
The onload and onunload events can be used to deal with cookies.
<body onload="checkCookies()">
The onchange Event
The onchange event are often used in combination with validation of input fields.
Below is an example of how to use the onchange. The upperCase() function will be called when a user
changes the content of an input field.
<input type="text" id="fname" onchange="upperCase()">
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</head>
<body>

Enter your name: <input type="text" id="fname" onchange="myFunction()">


<p>When you leave the input field, a function is triggered which transforms the input text to upper
case.</p>

</body>
</html>
The onmouseover and onmouseout Events
The onmouseover and onmouseout events can be used to trigger a function when the user mouses over,
or out of, an HTML element.
<!DOCTYPE html>
<html>
<body>
<div onmouseover="mOver(this)" onmouseout="mOut(this)"
style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
Mouse Over Me</div>
<script>
function mOver(obj) {
obj.innerHTML = "Thank You"
}

function mOut(obj) {
obj.innerHTML = "Mouse Over Me"
}
</script>
</body>
</html>
The onmousedown, onmouseup and onclick Events
The onmousedown, onmouseup, and onclick events are all parts of a mouse-click. First when a mouse-
button is clicked, the onmousedown event is triggered, then, when the mouse-button is released, the
onmouseup event is triggered, finally, when the mouse-click is completed, the onclick event is triggered.
<!DOCTYPE html>
<html>
<body>
<div onmousedown="mDown(this)" onmouseup="mUp(this)"
style="background-color:#D94A38;width:90px;height:20px;padding:40px;">
Click Me</div>

<script>
function mDown(obj) {
obj.style.backgroundColor = "#1ec5e5";
obj.innerHTML = "Release Me";
}
function mUp(obj) {
obj.style.backgroundColor="#D94A38";
obj.innerHTML="Thank You";
}
</script>
</body>
</html>
The onfocus()
Change the background-color of an input field when it gets focus.
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(x) {
x.style.background = "yellow";
}
</script>
</head> <body>
Enter your name: <input type="text" onfocus="myFunction(this)">
<p>When the input field gets focus, a function is triggered which changes the background-color.</p>
</body>
</html>

Example:
Create a web page using two image files, which switch between one another as the mouse pointer moves
over the images. Use the on Mouse Over and on Mouse Out
<!DOCTYPE html>
<html><head>
<script>
function lighton() {
document.getElementById('myimage').src = "bulbon.gif";
}
function lightoff() {
document.getElementById('myimage').src = "bulboff.gif";
}
</script>
</head> <body>
<img id="myimage" onmousedown="lighton()" onmouseup="lightoff()" src="bulboff.gif" width="100"
height="180" />
<p>Click mouse and hold down!</p>
</body>
</html>
EXCEPTION HANDLING
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c) Logical
Errors.

Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional programming languages
and at interpret time in JavaScript.

Runtime Errors
Runtime errors, also called exceptions, occur during execution (after compilation/interpretation).

Logical Errors
Logic errors can be the most difficult type of errors to track down. These errors are not the result of a
syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your
script and you do not get the result you expected.

The try...catch...finally Statement


• The try statement lets you test a block of code for errors.
• The catch statement lets you handle the error.
• The throw statement lets you create custom errors.
• The finally statement lets you execute code, after try and catch, regardless of the result.

JavaScript implements the try...catch...finally construct as well as the throw operator to handle
exceptions.
You can catch programmer-generated and runtime exceptions, but you cannot catchJavaScript syntax
errors.
Here is the try...catch...finally block syntax −
<script type="text/javascript">
<!--
try {
// Code to run
[break;]
}
catch ( e ) { // Code to run if an exception occurs
[break;]
}
[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//--> </script>
The try block must be followed by either exactly one catch block or one finally block (or one of both). When
an exception occurs in the try block, the exception is placed in e and the catch block is executed. The
optional finally block executes unconditionally after try/catch.
<!DOCTYPE html>
<html><body>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="message"></p>
<script>
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {
message.innerHTML = "Input is " + err;
}
}
</script> </body></html>
The finally Statement
The finally statement lets you execute code, after try and catch, regardless of the result:
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of the try / catch result
}

Example:
<!DOCTYPE html>
<html>
<body>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>

<p id="message"></p>
<script>
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "is empty";
if(isNaN(x)) throw "is not a number";
x = Number(x);
if(x > 10) throw "is too high";
if(x < 5) throw "is too low";
}
catch(err) {
message.innerHTML = "Input " + err;
}
finally {
document.getElementById("demo").value = "";
}
}
</script>
</body>
</html>
JSON
INTRODUCTION
JSON: JavaScript Object Notation.
JSON is a syntax for storing and exchanging data.
JSON is text, written with JavaScript object notation.
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:
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:
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.
// 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;
What is JSON?
• JSON stands for JavaScript Object Notation
• JSON is a lightweight data-interchange format
• JSON is "self-describing" and easy to understand
• JSON is language independent *
JSON uses JavaScript syntax, but the JSON format is text only.
Text can be read and used as a data format by any programming language.

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:
"name":"John"
Note: JSON names require double quotes. JavaScript names don't.
JSON - Evaluates to JavaScript Objects
The JSON format is almost identical to JavaScript objects.
In JSON, keys must be strings, written with double quotes:
JSON : { "name":"John" }
In JavaScript, keys can be strings, numbers, or identifier names:
JavaScript: { name:"John" }

JSON Values
In JSON, values must be one of the following data types:
• a string
• a number
• an object (JSON object)
• an array
• a boolean
• null
In JavaScript values can be all of the above, plus any other valid JavaScript expression, including:
• a function
• a date
• undefined
In JSON, string values must be written with double quotes:
{ "name":"John" }

In JavaScript, you can write string values with double or single quotes:
{ name:'John' }

JSON Uses JavaScript Syntax


Because JSON syntax is derived from JavaScript object notation, very little extra software is needed to work
with JSON within JavaScript.
With JavaScript you can create an object and assign data to it, like this:
Example:
var person = { name: "John", age: 31, city: "New York" };
You can access a JavaScript object like this:
person.name;
It can also be accessed like this:
person["name"];
Data can be modified like this:
person.name = "Gilbert";
It can also be modified like this:
person["name"] = "Gilbert";
JavaScript Arrays as JSON
The same way JavaScript objects can be used as JSON, JavaScript arrays can also be used as JSON.
JSON Files
• The file type for JSON files is ".json"
• The MIME type for JSON text is "application/json"

FUNCTION FILES
A common use of JSON is to read data from a web server, and display the data in a web page.
<div id="id01"></div>
<script>
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i<arr.length; i++) {
out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
<script src="myTutorials.js"></script>
Example Explained
1: Create an array of objects.
Use an array literal to declare an array of objects.
Give each object two properties: display and url.
Name the array myArray:
var myArray = [
{
"display": "JavaScript Tutorial",
"url": "https://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "https://www.w3schools.com/css/default.asp"
}
]

2: Create a JavaScript function to display the array.


Create a function myFunction() that loops the array objects, and display the content as HTML links:
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
Call myFunction() with myArray as argument:
myFunction(myArray);
3: Use an array literal as the argument (instead of the array variable):
Call myFunction() with an array literal as argument:
myFunction([
{
"display": "JavaScript Tutorial",
"url": "https://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "https://www.w3schools.com/css/default.asp"
}
]);

4: Put the function in an external js file


Put the function in a file named myTutorials.js:
myFunction([
{
"display": "JavaScript Tutorial",
"url": "https://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "https://www.w3schools.com/css/default.asp"
}
]);
Add the external script to your page (instead of the function call):
<script src="myTutorials.js"></script>

SQL
This example reads JSON data from a web server running PHP and MySQL:
<!DOCTYPE html>
<html>
<body>
<h1>Customers</h1>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "https://www.w3schools.com/js/customers_mysql.php";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Name +
"</td><td>" +
arr[i].City +
"</td><td>" +
arr[i].Country +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
</script>

</body>
</html>

The PHP Code on the Server


This is the PHP code running on the server:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");

$result = $conn->query("SELECT CompanyName, City, Country FROM Customers");

$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"Name":"' . $rs["CompanyName"] . '",';
$outp .= '"City":"' . $rs["City"] . '",';
$outp .= '"Country":"'. $rs["Country"] . '"}';
}
$outp .="]";

$conn->close();

echo($outp);
?>
Assignment

User sign Up Module


1. Create a registration page using HTML and CSS with right corner
of the page having current date and time.
2. For the same page and write validation function for registration
page and modify the onSubmit event Handler in the form code
to validate the following form fields:
• First Name
Must be entered
Must be character
• Last Name
Must be entered
Must be character
• Password
Must be entered
Password length should be between 6 to 20 characters
• Confirm Password
Must be entered
Password length should be between 6 to 20 characters
• Gender( Use radio button)
Must be selected
• Mobile Number
Must be entered
Must be in below format
XXX-XXX-XXXX or
XXX.XXX.XXXX or
XXX XXX XXXX
Assignment
• DOB
Must be entered
Must be in below format
• DD-MM-YYYY
Email Address
Must be entered
Email address must contain at least an @ 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:
Note: Password and Confirm password should be same.

3. If the user takes more than 3 mins to fill the form, it should
pop up an alert message saying 3 mins past.

NOTE: All JS scripts and CSS scripts should be created as external scripts.
ONLINE CERTIFICATIONS

SoloLearn – Javascript
https://www.sololearn.com/learning/1024
Assessment Schedule

Tentative schedule for the Assessment During 2020-2021 odd


semester

Name of the
S.NO Start Date End Date Portion
Assessment

1 UNIT TEST 1 UNIT 1

2 IAT 1 22.03.2021 27.03.2021 UNIT 1 & 2

3 UNIT TEST 2 UNIT 3

4 IAT 2 19.04.2021 24.04.2021 UNIT 3 & 4

5 REVISION 1 UNIT 5 , 1 & 2

6 REVISION 2 UNIT 3 & 4

7 MODEL 10.05.2021 20.05.2021 ALL 5 UNITS

89
Text Books & References
TEXT BOOK:

Deitel and Deitel and Nieto, “Internet and World Wide Web - How
to Program”, Prentice Hall, 5th Edition, 2011.

REFERENCES:

Stephen Wynkoop and John Burke “Running a Perfect Website”,


QUE, 2nd Edition, 1999.

Chris Bates, “Web Programming – Building Intranet Applications”,


3rd Edition, Wiley Publications, 2009.

Jeffrey C and Jackson, “Web Technologies A Computer Science


Perspective”, Pearson Education, 2011.

Gopalan N.P. and Akilandeswari J., “Web Technology”, Prentice Hall


of India, 2011.

UttamK.Roy, “Web Technologies”, Oxford University Press, 2011.


Thank you

Disclaimer:

This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not the
intended recipient you are notified that disclosing, copying, distributing or taking any action in reliance
on the contents of this information is strictly prohibited.

You might also like