0% found this document useful (0 votes)
245 views103 pages

M2 R5 Web Designing PDF

Web designing book

Uploaded by

pranavda2023
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)
245 views103 pages

M2 R5 Web Designing PDF

Web designing book

Uploaded by

pranavda2023
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/ 103

WEB

M2-R5:
Web Designing & Publishing.

JavaScript and Angular JS -जावाि ट और कोणीय जेएस


Introduction to Client Side Scripting Language, Variables in Java Script,Operators in JS, Conditions
Statements, JS Popup Boxes, JS Events, Basic FormValidations in JavaScript. Introduction to Angular
JS: Expressions, Modules and Directives.

[1]
Introduction to Client Side Scripting Language
It is also known as front-end language. Client-side scripting languages create the scripts that run on the
client-side in a web browser in front of the users. It is used to create static web pages.

Client-side scripting does not include any interaction with the server, the only interaction done is
receiving the data which was requested. It allows more interactivity with the clients using the browser
and is used to validate programs and functionality according to the request.

The client-side scripting languages are:


• Javascript.
• VB (Visual basic) Script.
• HTML (Hypertext Markup Language).
• CSS (Cascading Style Sheets).
• AJAX (Asynchronous JavaScript and XML (extensible markup language)).
• JQuery
• JS native
• React native

JavaScript Scripting Language

JavaScript is a scripting and client - site language. It is dynamicscriptinglanguageand used to make the
dynamic web page (website). It is lightweight and most commonly used as a part of web pages, whose
implementations allow client-side script to interact with the user.

JavaScript was invented by Brendan Eich in 1995. It was developed for Netscape 2 at Sun
microsystem. JavaScript made its first appearance in Netscape 2.0 in 1995 with the name LiveScript.
Later Netscape changed its name to JavaScript. The ECMA(European Computer Manufacturers
Association Script)-262 specifications defined a standard version of the core JavaScript language.

∗ It enables you to create dynamically updating content, control multimedia, animate images,
and pretty much everything else.
∗ It is interpreted, object-oriented and procedural scripting language.Its program interprets by
web browser. The JavaScript Translatorembedded in the web browser.
∗ JavaScript is a lightweight language and creating network-centric applications.
∗ Complementary to and integrated with Java.
∗ Complementary to and integrated with HTML.
∗ Open and cross-platform.
∗ Its program interacts with the userand it validate (check) the user data before send it to the
server. It performs data validation and other processing at client (user) site.
∗ 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.
∗ It is loosely (weakly) typed and full-fledged scripting language.
∗ It creates dynamically updating contents.
∗ It is text based language and used on client and server side both.

[2]
∗ With JavaScript, users can build modern web applications to interact directly without reloading
the page every time.
∗ JavaScript follows the syntax and structure of the C programming language. Thus, it is a
structured programming language.

 Application of JavaScript
∗ Client-side validation,
∗ Dynamic drop-down menus,
∗ Displaying date and time,
∗ Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and
prompt dialog box),
∗ Client side validation
∗ Back-end Data Loading
∗ Server Applications
∗ Interact with the user.
∗ Form validation
∗ Browser detection.
∗ Read and write cookies.
∗ Act upon events.

JavaScript Programming

Java script is a case sensitive scripting language and its program file extension is .js.

 <script> tag

It is a HTML tag and used to implement a client-side script (JavaScript). The java script code must be
writing inside <script> tag only. Using this tag we can write java script code either in <head> tag or in
<body> tag.

Attributes of <script> tag


Attribute Value Description

src URL Specifies the URL of an external java script file.

language scripting Specifies what scripting language you are using.


language Like: language="javascript"

Syntax:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> CAREER TECH ACADEMY</title>
<script language="javascript" type="text/javascript">

[3]
Java script code

</script>

</head>
<body>
<script language="javascript" type="text/javascript">

Javascript code

</script>
</body>
</html>

<script></script> tag will be used inside <h1> tag.


Ex:
<h1>
<script>
</script>
</h1>

Note: At end of each statement must be use semicolon (;) to writing another statement at the same
line.In Javascript, semicolons at the end of statements are optional.

 Writing the text or data on web page:


document:It is object represents your web page. The document object is the root node of the
HTML document.It is a command of javascript. It is used to display the text or data on the web page.

write(): It is a method and used to write the text of data on the web page. This method will be used
with document command using dot (.) sign as separator.

Ex:document.write();

We can write any types of data within double (“”) or single (‘’) quote mark in message format.

Syntax:document.write(“text of message”);

Example:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<script language="javascript" type="text/javascript">
document.write ("It is a first javascript program")
</script>
[4]
</body>
</html>
Output:

 Including HTML tags in a script


HTML tags can be included in a script using the document.write() command.

Syntax:document.write(“<html_tag> Message </html_tag>”);

Example:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<script language="javascript" type="text/javascript">
document.write ("<h1>Java script programming</h1>");
document.write ("It is first line");
document.write ("<br>It is second line");
</script>
</body>
</html>
Output:

 Comments in a javascript

The comment is a statement which will not be processed by the browser. Using comment thejava
script code would be easier to understand and navigate. Comments can be placed anywhere within
Javascript source code.

There are two types of comments.

(1) Single line comment: This comment is called inline comment. It will be start with double forward
slash (//).

[5]
(2) Multi-line line comment: Using it can be write multiplelines comment. Multi-line comments are
declared with a starting /* and an ending */

Example:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<script language="javascript" type="text/javascript">
document.write ("<h2>Comment example</h2>");
//single line comment
document.write("O Level");
/* O level is a 10+2
one year diploma */
</script>
</body>
</html>
Output:

 Handling browsers that do not support Javascript

There are older browsers still in use that do not recognize the <script> tag and consequently will not
be able to execute scripts. In such a case, the content inside the <script> tag will be displayed on the
page as regular text. To prevent this from happening, the content of a script can be placed within
comment tags. In such a case, older browsers that do not recognize the <script> tag will ignore the
script and the content inside the <script> tag will not be displayed on the page. Browsers that can
execute scripts will ignore the comments and execute the script anyway.

Example:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write("Here is some text");
[6]
//-->
</script>
</body>
</html>
Output:

 Linking external java script file

We can link external created java script file into html file. The src (source) attribute of <script> tag
will be used.

Step 1: First of all write java script code on editor (notepad++) and save with filename.js
extension.
cta.js
document.write("It is a java script code");
document.write("<br>It is a external java script file");

Step 2: In HTML file link the cta.js file using <script> tag.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript" src="cta.js">
</script>
</body>
</html>
Output:

 Javascript Data Types


JavaScript provides different data types to hold different types of values. There are two types of data
types in JavaScript.

(a) Primitive data type.

(b) Non-primitive (reference) data type.

[7]
(a) Primitive data type: It is predefine or inbuilt data type. It is also called primary data type. There
are following primitive data types in JavaScript.

Data Description Example


(class)
Type

string It is single or group of characters. Class type is “A”, “javascript”


string.

number Integer (int) value. Class type is number. 234, 2244

Floating point (float) value. Class type is number. 78.5, 456.6710

boolean represents boolean value either false or true. Class true or false
type is boolean.

undefined represents undefined value. If variable does not Ex: var a;


initialized then treated as undefined class.

object It indicating that a variable has no object. In null


undefined variable we can store null value. Ex: var
a=null;

object It indicating that a variable points no object. var aa=new Array(3);


document.write(typeof(aa));

(b) Non-primitive (reference) data type: It is user define data type. It is also called secondary data
type. There are following non-primitive data types in JavaScript.

There are the following five types of reference types in Java:

Non- Description
primitive
data Type

Class It is a set of instructions. It describes the content of the object.

Array It provides the fixed-size data structure that stores the elements of the same type.

Annotations It provides a way to associate metadata with program elements.

Interface It is implemented by Java classes.

Enumeration It is a special kind of class that is type-safe. Each element inside the enum is an
instance of that enum.

 Variable in Javascript
The variable is identifier or name of memory space. Variables are used to store data, like string of text,
numbers, etc. The data or value stored in the variables can be set, updated, and retrieved whenever needed.

[8]
Naming conventions (rules) for declare the variables
These are the following rules for naming a JavaScript variable:
• A variable name can includes letter, underscore (_), or digit.
• A variable name cannot start with a number.
• A variable name cannot contain spaces.
• A variable name cannot be a JavaScript keyword or a JavaScript reserved word.

Note: Variable names in JavaScript are case sensitive, it means abc and ABC are two different variables.

 Declaration of variable:
The var keyword is used to declare the variable. Using comma (,) sign cab separate the multiple variables. By
default it has stored ‘undefined’ value. The var provides function scop variable inside function.
Syntax: var variable_name;
Example: var a;
var a,b,c;

 Definition of variable:
We can store the value into variable using assignment operator.

Syntax: variable_name=value;
Example: a=100; b=“rajesh kumar”; c=null;

 Declaration and definition of variable together:


Syntax: var variable_name=value;
Example: var a=100; var b=“rajesh kumar”; var c=null;

Print the value of variable:

To print the value the variable must be write inside document.write() method. More than one variables
will be separate by comma (,) sign.

Syntax: document.write(variable_1,variable_2, variable_n);

Example:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
document.write("<h3>Printing the value of variable</h3>");
var s1=9.5;
document.write(s1);
</script>
</body>

[9]
</html>
Output:

Print the value of variable with message:

Between message and variable the plush (+) or , (comma) sign will be use as separator.

Syntax: document.write(“Message”+variable_name);

Example:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
document.write("<h3>Printing the message with value of variable</h3>");
var roll=100,name="Rajesh Kumar";
document.write("Rollnumber of student is: "+roll);
document.write("<br>Name of student is: "+name);
</script>
</body>
</html>
Output:

 typeof() function:
This function is used to return the data type of given value.
Syntax: variable=typeof(value/variable);

Example:
<!doctype html>
<html>
<head><meta charset="utf-8">

[10]
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<script language="javascript" type="text/javascript">
var a=5,b=89.5,c="Rajesh Kumar";
document.write("Value of a is : "+a);
document.write("<br>Type of a is : "+typeof(a));
document.write("<br>Value of b is : "+b);
document.write("<br>Type of b is : "+typeof(b));
document.write("<br>Value of c is : "+c);
document.write("<br>Type of c is : "+typeof(c));
</script>
</body>
</html>
Output:

 isNaN() function:
This function is known as ‘is Not a Number’ function. This and used to find out that variable stored
the number of not. It returns true if the variable does not store number. It returns false if the variable
stored the number.

Syntax:variable= isNaN(variable);

Example:
<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
var a=90,b="CTA";
document.write("The value of a is: "+a);
var x=isNaN(a);
document.write("<br>The value of a is a number: "+x);
document.write("<br>");
document.write("The value of b is: "+b);
var x=isNaN(b);
document.write("<br>The value of b is not a number: "+x);
</script>

[11]
</body>
</html>
Output:

 Storage classes of variable

In the javascript storage classes are the another type of variable and used to store the value. There are
two types of storage classes.

(1) lets torage class.


(2) const storage class.

(1) let storage class:


In JavaScript, let is a keyword that is used to declare a block scoped variable. The let keyword was
introduced in ES6 (2015). It work line normal variable. By default it has stored ‘undefined’ value.
The let provides block scope variable.

Variables defined with let have Block Scope.

Syntax: let variable_name;


Example: let a;
let a,b,c;
Example:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
document.write("<h3>Let Variable</h3>");
let roll=100,name="Rajesh Kumar";
document.write("Rollnumber of student is: "+roll);
document.write("<br>Name of student is: "+name);
</script>
</body>
</html>
Output:

[12]
 Variables defined with let cannot be redeclared.

Example:
let x = "John Doe";

let x = 0;// SyntaxError

(2) const storage class.


ES6 (2015) introduced the const keyword, which is used to define a new variable in
javascript. Variables defined with const cannot be redeclared.Variables defined with const cannot be
reassigned.Variables defined with const have block scope. JavaScript const variables must be assigned
a value when they are declared. It`s value can be changed into the program.

Syntax: const variable_name=value;


Example: const a=9;
const a=2,b=78;

Example:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
document.write("<h3>Const Variable</h3>");
const roll=100,name="Rajesh kumar";
document.write("Rollnumber of student is: "+roll);
document.write("<br>Name of student is: "+name);
</script>
</body>
</html>
Output:

[13]
 Variables defined with const cannot be reassigned.

Example:
const x = "John Doe";

x =100;// SyntaxError

 Printing the data using HTML tags through ID


ID: The id is the attribute of html tag and used to define the id of html tag. The id can be used to
access the particular html tag. The id name will be as the variable name.

Syntax:<html_tag id= “name of id”></html_tag>

Example:<p id=“p1”></p>

To print the data using HTML tag, there are following methods are used.

document: The document object is used to write the text or data on the web page. It represents the
web page.

 getElementById() method:
It is a method of the document object (DOM (Document Object Method) related method).
DOM is a programming API (Application Programming Interface). It is mainly used to manipulate or
to get some info from an element on to your document.

This method returns an Element object representing the element whose id property matches the
specified string. Since element ID is used to access to a specific element quickly. If values are n the n
ID is used to print n value.

This method returns an element (DOM element) with a specified value. It returns the null if the
element does not exist.

The ID should be unique within a page. However, if more than one element with the specified ID
exists, it returns the first element in the javascript code.

This method will be write inside the <body> tag after another ID related tag.

Syntax: document.getElementById(“html tag id”)


Example:

<h1 id="id1"></h1>
document.getElementById(“html tag id”)

Note: This method must be writing into <body> tag after HTML tag (using <script>
tag).

 Element.inner HTML:

[14]
The Element property innerHTML gets or sets the HTML or XML markup contents within the
element.

It is used two purpose. First is to get the html contents as string. Second is to set contents into html
elements.

The element will be document.getElementById("id1").

Syntax: document.getElementById("id1").innerHTML

 Example: Display the value using ID

Syntax: document.getElementById(“html tag id”).innerHTML=value.

Example:
<!doctype html>
<html>
<head><meta charset="utf-8">
<title> CAREER TECH ACADEMY</title>
</head>
<body>
<h1 id="id1"></h1>
<script language="javascript" type="text/javascript">
document.getElementById("id1").innerHTML=100;
</script>
</body>
</html>
Output:

• Printing Text value and data values together:


The text value must be write within double (“”) or single (‘’) quote mark. The data value or variable
will be writing as normal. Between the text value and data value the plush (+) sign will be used.

Syntax:document.getElementById(“html tag id”).innerHTML= “text”+variable_name.

Example:
<!doctype html>
<html>
<head><meta charset="utf-8">
<title> CAREER TECH ACADEMY</title>
</head>
<body>
<h1 id="id1"></h1>

[15]
<script language="javascript" type="text/javascript">
var roll=90;
document.getElementById("id1").innerHTML='The rollnumber is : '+roll;
</script>
</body>
</html>
Output:

 To print n values the n HTML tags will be used.

Example:
<!doctype html>
<html>
<head><meta charset="utf-8">
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<h1 id="id1"></h1>
<h1 id="id2"></h1>
<script language="javascript" type="text/javascript">
var roll=90,name="Rajesh Kumar";
document.getElementById("id1").innerHTML='The rollnumber is : '+roll;
document.getElementById("id2").innerHTML='The name is : '+name;
</script>
</body>
</html>
Output:

 Using <span> tag


The <span> tag has not own meaning so it can be used to specify the id of any HTML tag.
Example:
<!doctype html>
<html>
<head><meta charset="utf-8">
<title> CAREER TECH ACADEMY </title>
</head>
<body>

[16]
<h1>
Information of Student
<span id="id1"></span>
</h1>
<script language="javascript" type="text/javascript">
var roll=100;
document.getElementById("id1").innerHTML='<br>The rollnumber is : '+roll;
</script>
</body>
</html>
Output:

Display Message Using Popup Boxes


Javascript provides a popup boxes to interact with the user. There are following popup boxes;
(1) alert box.
(2) confirmbox.
(3) prompt box.

(1) alert box:


The alert() function is used to display the message in alert popup box.The text value must be write
within double (“”) or single (‘’) quote mark. The data value or variable will be writing as normal.
Between the text value and data value the plush (+) sign will be used.
Syntax:alert( “text”+variable_name);

Example:
<!doctype html>
<html>
<head><meta charset="utf-8">
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<script language="javascript" type="text/javascript">
var roll=100;
alert("Information of Student");
alert('The rollnumber is : '+roll);
</script>
</body>
</html>
Output:

[17]
Using onclick event we can print the message with alert popup box.
<input type="button" onclick="alert('Hi, I am an alert box!');" value="Click here for a message" />

(2) confirm box:


It is a confirmation box and can be displayed using confirm() function. It is used to display the
message and user makes a choice. A confirmation box will appear will with an "OK" button and a
"Cancel" button. Different actions will occur depending on what button the user clicks. If click on
"OK" button then return true value and if click on "Cancel" button then return false.

The text value must be write within double (“”) or single (‘’) quote mark. The data value or variable
will be writing as normal. Between the text value and data value the plush (+) sign will be used.

Syntax:variable=confirm( “text”+variable_name);

Example:
<!doctype html>
<html>
<head><meta charset="utf-8">
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<script language="javascript" type="text/javascript">
var roll=100,x;
x=confirm('The rollnumber is : '+roll);
document.write("You have press OK button ?: "+x);
</script>
</body>
</html>
Output:

(3) prompt box:


A prompt box is used to get data from the user. A prompt box will appear with an "OK" button and a
"Cancel" button. Different actions will occur depending on what button the user clicks. If the user
clicks the "OK" button, then entered value will be stored into the variable. If the user clicks the

[18]
"Cancel" button, a null value (empty string) will be stored into the variable. It takes two text
arguments, which will be display on web page.The second argument is optional.

A prompt box can be displayed using prompt() function.

The prompt() function provides the entered value in string format. To perform the arithmetic operation
must be convert that value in number format.

Syntax:variable=prompt( “text message”,“text message”);

Example:
<!doctype html>
<html>
<head><meta charset="utf-8">
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<script language="javascript" type="text/javascript">
var a,b,c;
a=prompt("Enter rollnumber ","Write rollnumber here:");
document.write("<br>Entered value is : "+a);
document.write("<br>Type of entered value is : "+typeof(a));
b=prompt("Enter name ","Write name here:");
document.write("<br>Entered name is : "+b);
document.write("<br>Type of entered name is : "+typeof(b));
c=prompt("Enter marks ","Write marks here:");
document.write("<br>Entered marks is : "+c);
document.write("<br>Type of entered marks is : "+typeof(c));
</script>
</body>
</html>
Output:

 Converting the value into number format


The prompt popup box is provides all types of values into string data type format. On the string type
value we cannot performs arithmetic operation. There are following three functions are used for this
purpose.
(1) parseInt() function.
(2) parseFloat() function.
(3) eval()function.
(4) Number()function.

[19]
(1) parseInt() function: It converts the integer value, which is in string format into number (int)
format. It returns only integer value if value is float.
Syntax:variable=parseInt( value/variable );

Example:
<!doctype html>
<html>
<head><meta charset="utf-8">
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<script language="javascript" type="text/javascript">
var a,x;
a=prompt("Enter integer value ","Write value here:");
document.write("<br>Entered value is : "+a);
document.write("<br>Type of entered value is : "+typeof(a));
document.write("<br>After conversion----------- ");
x=parseInt(a);
document.write("<br>Type of entered value is : "+typeof(x));
</script>
</body>
</html>
Output:

(2) parseFloat() function.: It converts the integer value, which is in string format into number (float)
format.
Syntax:variable=parseFloat(value/variable);

Example:
<!doctype html>
<html>
<head><meta charset="utf-8">
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<script language="javascript" type="text/javascript">
var a,x;
a=prompt("Enter float value ","Write value here:");
document.write("<br>Entered value is : "+a);

[20]
document.write("<br>Type of entered value is : "+typeof(a));
document.write("<br>After conversion -----------");
x=parseFloat(a);
document.write("<br>Type of entered value is : "+typeof(x));
</script>
</body>
</html>
Output:

Example: (parseInt() and parseFloat() )


<!doctype html>
<html>
<head><meta charset="utf-8">
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<script language="javascript" type="text/javascript">
var a,b;
a=parseInt(prompt("Enter integer value "));
document.write("<br>Entered value is : "+a);
document.write("<br>Type of entered value is : "+typeof(a));
document.write("<br>------------------------");
b=parseFloat(prompt("Enter float value "));
document.write("<br>Entered value is : "+b);
document.write("<br>Type of entered value is : "+typeof(b));
</script>
</body>
</html>
Output:

(3) eval() function: It converts the number (integer or float) value, which is in string format into
number format . So this function can be used for both integer and float types of numbers.
Syntax:variable=eval( value/variable );

[21]
Example:
<!doctype html>
<html>
<head><meta charset="utf-8">
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<script language="javascript" type="text/javascript">
var a,b;
a=eval(prompt("Enter integer value "));
document.write("<br>Entered value is : "+a);
document.write("<br>Type of entered value is : "+typeof(a));
document.write("<br>------------------------");
b=eval(prompt("Enter float value "));
document.write("<br>Entered value is : "+b);
document.write("<br>Type of entered value is : "+typeof(b));
</script>
</body>
</html>
Output:

Example: Take rollnumber, name and two subjects of marks. Print rollnumber, name
and total of marks?
<!doctype html>
<html>
<head><meta charset="utf-8">
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<script language="javascript" type="text/javascript">
var a,b,c,d,e;
document.write("<br>Enter student information:");
a=eval(prompt("Enter rollnumber : "));
b=prompt("Enter name : ");
c=eval(prompt("Enter sub1 mark : "));
d=eval(prompt("Enter sub2 mark : "));
document.write("<br>------------------------");
document.write("<br>Information of student :");
document.write("<br>Rollnumber is : "+a);
document.write("<br>Name is : "+b);
e=c+d;
[22]
document.write("<br>Total of sub1 and sub2 marks is : "+e);
</script>
</body>
</html>
Output:

(4) Number() function: It converts the number (integer or float) value, which is in string format into
number format only (not in integer or flaot). So this function can be used for both integer and float
types of numbers.
Syntax: variable=Number( value/variable );

Example:
<!doctype html>
<html>
<head><meta charset="utf-8">
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<script language="javascript" type="text/javascript">
var a,b;
a=Number(prompt("Enter integer value "));
document.write("<br>Entered value is : "+a);
document.write("<br>Type of entered value is : "+typeof(a));
document.write("<br>------------------------");
b= Number(prompt("Enter float value "));
document.write("<br>Entered value is : "+b);
document.write("<br>Type of entered value is : "+typeof(b));
</script>
</body>
</html>
Output:

[23]
 Operator in JavaSrcript
An operator is capable of manipulating a certain value or operand. Operators are used to perform
specific mathematical and logical computations on operands. In other words, we can say that an
operator operates the operands.

There are following types of operators in JavaScript.

(1)Arithmetic Operators
(2)Assignment Operators
(3)Comparison (Relational) Operators
(4)Logical Operators
(5)Bitwise Operators
(6) Ternary Operators
(7) Special Operators
(1) Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on the operands. It is binary operator
because it performs the operation on the two values. The following operators are known as JavaScript
arithmetic operators.

Operator Description Example


+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
/ Quotient of Division 20/10 = 2.000000
% Modulus (Remainder) 20%10 = 0
** Exponentiation (ES2016). Power of value 4**3=64 (4*4*4)
++ Increment (Increase the value by 1) var a=10; a++; Now a = 11
-- Decrement (Decrease the value by 1) var a=10; a--; Now a = 9

Note: The ++ and -- are unary operator because it performs the operation on the one values.

Example: (Arithmetic operators)


<!doctype html>
<html>
<head><meta charset="utf-8">
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<script language="javascript" type="text/javascript">
[24]
var a,b;
document.write("<h1>Arithmetic operators</h1> ");
a=eval(prompt("Enter first number : "));
b=eval(prompt("Enter second number : "));
document.write("<br>First number: "+a);
document.write("<br>Second number: "+b);
document.write("<br>---------------------------");
document.write("<br>Addition (a+b): "+(a+b));
document.write("<br>Subtraction (a-b): "+(a-b));
document.write("<br>Multiplication (a*b): "+(a*b));
document.write("<br>Division (a/b): "+(a/b));
document.write("<br>Modulus (Remainder) (a%b): "+(a%b));
document.write("<br>Exponentiation (a**3): "+(a**3));
a++;
document.write("<br>Increment (a++) a: "+(a));
a--;
document.write("<br>Decrement (a--) a: "+(a));
</script>
</body>
</html>
Output:

(2) Assignment Operators


Assignment operators assign values to JavaScript variables.Assigns right operand value to left
operand. It is binary operator because it performs the operation on the two values.The following
operators are known as JavaScript arithmetic operators or shorthand or compound operator.

Syntax: operand arithmetic_operator = value/operand

Operator Example Same As


(Only two variables will be used) (Three variables will be
used)
= (Simple assignment) x=y x=y
+= x += y x=x+y
[25]
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y

Example:(Assignment operators)
<!doctype html>
<html>
<head><meta charset="utf-8">
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<script language="javascript" type="text/javascript">
var a=4,b=3;
document.write("<h1>Assignment operators</h1> ");
document.write("<br> a is : "+a);
document.write("<br> b is : "+b);
a+=b;
document.write("<br>Addition (a+=b), a is : "+a);
document.write("<br> ----------------------------");
a=5,b=3;
document.write("<br> a is : "+a);
document.write("<br> b is : "+b);
a-=b;
document.write("<br>Subtraction (a-=b), a is : "+a);
document.write("<br> ----------------------------");
a=7,b=4;
document.write("<br> a is : "+a);
document.write("<br> b is : "+b);
a*=b;
document.write("<br>Multiplication (a*=b), a is : "+a);
document.write("<br> ----------------------------");
a=13,b=5;
document.write("<br> a is : "+a);
document.write("<br> b is : "+b);
a/=b;
document.write("<br>Division (a/=b), a is : "+a);
</script>
</body>
</html>
Output:

[26]
(3) Comparison (Relational) Operators
The JavaScript comparison operator compares the two operands. It returns the result in logical value
either true or false. If comparison is true then return true otherwise return false. It is binary operator
because it performs the operation on the two values. It is called shorthand or compound assignment
operator. The comparison operators are as follows:
(( The comma sign will be use in between expression and message. ))
Operator Description Example

== Is equal to 10==20 = false

=== Identical (equal and of same type) 10===20 = false


(It checks that both values as well as type of
variables)
!= Not equal to 10!=20 = true

!== Not Identical 20!==20 = false

> Greater than 20>10 = true

>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false

<= Less than or equal to 20<=10 = false

Example:(Comparison operator)
<!doctype html>
[27]
<html>
<head><meta charset="utf-8">
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<script language="javascript" type="text/javascript">
var a,b;
document.write("<h1>Comparison operators</h1> ");
a=eval(prompt("Enter first number : "));
b=eval(prompt("Enter second number : "));
document.write("<br>First number: "+a);
document.write("<br>Second number: "+b);
document.write("<br>---------------------------");
document.write("<br> a is equal to b (a==b): "+(a==b));
document.write("<br> a identical (equal and of same type) b (a===b):
"+(a===b));
document.write("<br>a is not equal to b (a!=b): "+(a!=b));
document.write("<br>a is not Identical with b (a!==b): "+(a!==b));
document.write("<br> a is greater than b (a>b): "+(a>b));
document.write("<br>a is greater than or equal to b (a>=b): "+(a>=b));
document.write("<br>a less than b : "+(a<b));
document.write("<br>a less than or equal to b (a<=b): "+(a<=b));
</script>
</body>
</html>
Output:

(4) Logical Operators


The JavaScript logical operator compares the two relational expressions. It returns the result in logical
value either true or false. If comparison is true then return true otherwise return false. It is binary
operator because it performs the operation on the two values.The logical operators are as follows:

(1) && (Logical AND) operator:It returns true if left_exp and right_exp of the conditions are true,
otherwise return false.
[28]
Syntax: variable=left_exp && right_exp;

(2) || (Logical OR) operator: It returns false if left_exp and right_exp of the conditions are false,
otherwise return true.

Syntax: variable=left_exp || right_exp;

(3) ! (Logical NOT) operator:It reverses the boolean result of the operand (or condition). It returns
true if the condition is false andreturns false if the condition is true. It is unary operator.

Syntax: variable=! Exp;

S.N. Operator Description Example

1 && Logical AND (10==20 && 20==33) = false

2 || Logical OR (10==20 || 20==33) = false

3 ! (unary) Logical Not !(10==20) = true

Example:(Logical operator)
<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
var a=4,b=3,c;
document.write("<h1> Logical operator </h1> ");
document.write("<br>First number: "+a);
document.write("<br>Second number: "+b);
document.write("<br>---------------------------");

document.write("<br>-------- Logical && AND --------");


c=a>b && b<a;
document.write("<br>"+c);
document.write("<br>-------- Logical || OR --------");
c=a<b || b>a;
document.write("<br>"+c);
document.write("<br>-------- Logical ! NOT --------");
c=!(a<b);
document.write("<br>"+c);
</script>
</body>
</html>
Output:

[29]
(5) Bitwise Operators
This operator works on the binary values of the operands (values). It first converts the operands
(values) into binary digits then on binary values it performs the operation.

Bitwise operators work on 32 bits binary numbers.Any numeric operand in the operation is converted
into a 32 bit binarynumber. The result is converted back to a JavaScript decimal number.

Operators Description Example Same as Result in Decimal


Binary in Binary

& AND 5&1 0101 & 0001 0001 1

| OR 5|1 0101 | 0001 0101 5

~ (Tilde) NOT ~5 ~0101 1010 10


It uses
complement
1`s and 2`s.
^ (Caret) XOR 5^1 0101 ^ 0001 0100 4
It performs
addition
without
carry.
<< left shift 5 << 1 0101 << 1 1010 10

>> right shift 5 >> 1 0101 >> 1 0010 2

>>> unsigned right 5 >>> 1 0101 >>> 1 0010 2


shift

The examples above uses 4 bits unsigned examples. But JavaScript uses 32-bit signed numbers.
Because of this, in JavaScript, ~ 5 will not return 10. It will return -6.
~00000000000000000000000000000101 will return 11111111111111111111111111111010.

Example:(Bitwise Operators)
<!doctype html>
<html>

[30]
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
var a=9,b=5,c;
document.write("<h1> Bitwise operator </h1> ");
document.write("<br>-------- Bitwise & AND --------");
c=a&b;
document.write("<br>"+c);
document.write("<br>-------- Bitwise | OR --------");
c=a|b;
document.write("<br>"+c);
document.write("<br>-------- Bitwise ~ NOT --------");
c=~a;
document.write("<br>"+c);
document.write("<br>-------- Bitwise << Left Shift --------");
c=a<<2;
document.write("<br>"+c);
document.write("<br>-------- Bitwise >> Right Shift --------");
c=a>>2;
document.write("<br>"+c);
</script>
</body>
</html>
Output:

(6) Ternary Operators


The ternary operator is used to perform the operation on condition basis. This operator includes three
operands: a condition followed by a question mark (?) sign, and two expressions separated by the
colon (:). The first expression is executed when the condition is true, and the second expression is
executed when the condition is false.The working of this operator is the same as the if-else conditional
statement. We can say that it is the shortcut of the if-else. It is called conditional operator.
Syntax: variable=condition ? <first_expression> : <second_expression>;

[31]
Example: (Ternary operator)
<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
var a=9,c;
document.write("<h1> Ternary operator </h1> ");
document.write("<br> a is: "+a);
c = ( a % 2 == 0) ? 'Even Number' : 'Odd Number';
document.write("<br>"+a+" is a :"+c);
</script>
</body>
</html>
Output:

(7) Special Operators


The following operators are known as JavaScript special operators.

Operator Description

, Comma Operator allows multiple expressions to be evaluated as single statement.

delete Delete Operator deletes a property from the object.

instanceof It checks that object is an instance of given type (class) or not.

new It creates an instance (object) of class.

typeof It checks the type of object.

void It specify that function does not return the value.

String in JavaScript

The string is values which must be write within single of double quote marks. Its data type is
string.Any values can be written in string format.

Syntax:variable= “string value”;

Example:
[32]
<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
var a='CTA',b="CTA";
document.write("The value of a is: "+a);
document.write("<br>The data type of a is : "+typeof(a));
document.write("<br>The value of b is: "+b);
document.write("<br>The data type of b is : "+typeof(b));
</script>
</body>
</html>
Output:

String concatenation

We can concatenate the two strings using plush (+) sign and plush assign (+=) operator.

Example:
<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
var a="Career",b="Tech",c;
c=a+" "+b;
document.write("The value of a is: "+a);

document.write("<br>The value of b is: "+b);


document.write("<br>After concatenation a and b is : "+c);
</script>
</body>
</html>
Output:

 Decision Making Statements

[33]
It is also known as conditional statements. If need to checks the value of variable then must be uses the
conditions. There are following types of conditional statements.

(1)if statement.
(2)if...else statement.
(3)if...else if... statement.

(1) if statement:This statement is used to apply the condition with the value. If the given condition is
true then if block of statement will be execute. If the given condition is false then if block of statement
will not be execute.

Syntax:

if (condition)
{
Statement(s) to be executed if expression is true;
}

OR

if (condition)
Statement(s) to be executed if expression is true;

Note: For single line statement not required curly bracket.

Example:Find out the given number is even of odd?


<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
var a;
a=eval(prompt("Enter any one number : "));
if(a%2==0)
{
alert("Number is even : "+a);
}
if(a%2!=0)
{
alert("Number is odd : "+a);
}
</script>
</body>
</html>
Output:

[34]
(2) if….else statement:It have two statements the first is if and second is else. The statement is
used to apply the condition with the value. If the given condition is true then if block of statement will
be execute. If the given condition is false then only the block of else statement will be execute. So at a
time only one statement will be execute either if block of statement will be execute or else black of
statement will be execute

Syntax:

if (condition)
{
Statement(s) to be executed if expression is true;
}
else
{
Statement(s) to be executed if expression is false;
}

Example: Find out the given number is even of odd?


<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
var a;
a=eval(prompt("Enter any one number : "));
if(a%2==0)
alert("Number is even : "+a);
else
alert("Number is odd : "+a);
</script>
</body>
</html>
Output:

[35]
(3) if...else if... statement: This statement is used to test a variable for more than one value at a
time. Using this we can apply multiple conditions on a single variable. It is also known as if else if
ladder.

Syntax:
if(condition)
{
Statements;
}
else if(condition)
{
Statements;
}
else if(condition)
{
Statements;
}

Example: Take a number which will be day of week of number. Print the day of
weekaccording to given number? ( 1 means Monday, 2 means Tuesday and so on).
<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
var a;
a=eval(prompt("Enter any one number between 1 to 7: "));
if(a==1)
alert("Monday");
else if(a==2)
alert("Tuesday");
else if(a==3)
alert("Wednesday");
else if(a==4)
alert("Thursday");
else if(a==5)
alert("Friday");

[36]
else if(a==6)
alert("Saturday");
else if(a==7)
alert("Sunday");
else
alert("Wrong number : "+a);
</script>
</body>
</html>
Output:

 The switch statement


The switch statement is specifically designed for comparing one variable to a number of possible
values. It can be thought of as a substitute for the if, else if, else structure.

There is an important keyword used within the switch structure.


(1) switch():This statement is used to write the variable witch of the value will be check.
(2) case: This statement is used to write the possible values which can be in switch variable.
(3) break: This statement is used to through the control to the outside of the switch statement.
(4) default: It is work like else statement. This statement will be execute at the last when all the above
case statement will not be execute.

Syntax:
switch(variable)
{
case possible value: statement; break;
case possible value: statement; break;
-------------------
-------------------
case possible value: statement; break;
default: statement;
}

Example 1: Take a number which will be day of week of number. Print the day of
weekaccording to given number? ( 1 means Monday, 2 means Tuesday and so on).
<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
[37]
<script language="javascript" type="text/javascript">
var a;
a=eval(prompt("Enter any one number between 1 to 7: "));
switch(a)
{
case 1:alert("Monday");break;
case 2:alert("Tuesday");break;
case 3:alert("Wednesday");break;
case 4:alert("Thursday");break;
case 5:alert("Friday");break;
case 6:alert("Saturday");break;
case 7:alert("Sunday");break;
default:alert("Wrong number : "+a);
}
</script>
</body>
</html>
Output:

Example 2: Take one character and find out that character is vowel or consonant?
<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
var a;
a=prompt("Enter any one character: ");
switch(a)
{
case 'a':alert("Vowel");break;
case 'e':alert("Vowel");break;
case 'i':alert("Vowel");break;
case 'o':alert("Vowel");break;
case 'u':alert("Vowel");break;
default:alert("Consonant : "+a);
}
</script>
</body>
</html>

[38]
Output:

 Loop
It also known as repetitive or iterative statement. Loops are specifically designed to perform repetitive
tasks with one set of code. It means when we need to execute one or more lines of code more than one
times again and again then we can apply loop statement. There are following types of loops.

(1)The for loop.


(2)The for in loop.
(3)The while loop.
(4)The do-while loop.

(1) The for loop


The for loop is used to repeat a task a set number of times. Using this loop we can execute a set of
code again and again until given condition will not be false.

In this loop have three pars and each part are separated by semicolon (;).

(a) Variable initialization: The first part of the loop which initializes the variable at the beginning of
the loop to some value. This value is the starting point of the loop. This part will be executes only
once.

(b) Condition: The second part of the loop, and it is the part that decides whether the loop will
continue running or not. While the condition in the loop is true, it will continue running. Once the
condition becomes false, the loop will stop.

(c) Increment or decrement:It changes the value of the variable created in the variable initialize part
of the loop. This part is used to move loop the ahead.

Syntax:

for(variable = initial_value; condition; a_variable_increment or decrement)


{
Statements;
Statements;
}

Example 1: Print 1 to 10 natural number?


<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>

[39]
<body>
<script language="javascript" type="text/javascript">
var i;
document.write("1 to 10 natural numbers: <br><br>");
for(i=1;i<=10;i++)
document.write(i+" ");
</script>
</body>
</html>
Output:

Example 2: Take one number from keyboard and print table of that number?
<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
var n,i;
n=eval(prompt("Enter any one number: "));
document.write("The table of "+n+" is: <br><br>");
for(i=1;i<=10;i++)
document.write((n*i)+" ");
</script>
</body>
</html>
Output:

 Nested for loop


The for loop can use inside another for loop is called nested for loop or loop inside loop. The outer for
loop is work for rows and inner for loop is work for column.
Syntax:

for(variable = initial_value; condition; a_variable_increment or decreament)


{
for(variable = initial_value; condition; a_variable_increment or decreament)
{
[40]
Statements;
Statements;
}

Example:Print the following pattern?

<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
var i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
document.write("*");
}
document.write("<br>");
}
</script>
</body>
</html>
(2) The for in loop
This loop is used to iterate the properties of an object. This loop is used to accessed the each elements
of the object like array. It has following competent.

Index_variable: It is a starting point of the loop. It increments by one automatically by one to the
next element of the object.

In:It is a keyword and used to specify the object from which, the index will read the value. The index
will continue until the last element will be read from the object.

Object: It a name of object from which, the index will read the value. It can be object of array.

Syntax:
for(index_variable in object)
{
Statements;

[41]
Statements;
}

Example: Print each element of the array?


<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
var num=[45, 4, 9, 16, 25];
let i;
document.write("Values of the array are:");
for (i in num)
{
document.write("<br>"+num[i]);
}
</script>
</body>
</html>
Output:

(3) The while loop


The while loop works same as for loop. The while loop repeats a segment of code a specific number of
times. The code within a while loop will execute while the specified condition is true. It is called
entry-controlled loop.

It has also the three parts like for loop, variable initialization, condition and increment or decrement.

Syntax:
variable = initial_value;
while(condition)
{
Statements;
Statements;
a_variable_increment or decrement;
}

Example: Print 10 to 1 reverse number?


<!doctype html>
<html>
[42]
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
document.write("<h3> Reverse the number 10 to 1 </h3>");
var i;
i=10;
while(i>=1)
{
document.write(i+" ");
i--;
}
</script>
</body>
</html>
Output:

 Nested while loop

It is a like nested for loop. The while loop can use inside another while loop is called nested while
loop or loop inside loop. The outer while loop is work for rows and inner while loop is work for
column.
Syntax:

variable = initial_value;
while(condition)
{
variable = initial_value;
while(condition)
{
Statements;
Statements;
a_variable_increment or decreament;
}
Statements;
a_variable_increment or decreament;
}

[43]
Example: Print the following pattern?

<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
var i,j;
i=5;
while(i>=1)
{
j=1;
while(j<=i)
{
document.write("*");
j++;
}
i--;
document.write("<br>");
}
</script>
</body>
</html>

(4) The do-while loop


The do-while loop is very similar to the while loop, but it does things in reverse order. The mechanism
of the while loop is - while a condition is true, perform a certain action. The mechanism of the do-
while loop is - perform a certain action while a condition is true. Furthermore, the code within a do-
while loop will always execute at least once, even if the specified condition is false. This is because
the code is executed before the condition is tested.

It has also the three parts like while loop, variable initialization, condition and increment or decrement.

Syntax:
variable = initial_value;
do
{
Statements;
Statements;
a_variable_increment or decrement;

[44]
}while(condition);

Example:Print fibonacci series upto given limit?


<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
document.write("<h3>Fibonacci Series </h3>");
var a=0,b=1,c=0,n;
n=eval(prompt("Enter upper limit to print fibonacci series"));
document.write(a+" ");
document.write(b+" ");
do
{
c=a+b;
a=b;
b=c;
document.write(c+" ");
}while(c<=n);

</script>
</body>
</html>
Output:

 Array
An array is a collection of similar data elements stored at contiguous memory
locations.An array data structure, or simply an array, is a data structure consisting of a collection of
elements, each identified by at least one array index or key. An array is stored such that the position of
each element can be computed from its index number.

Array creation:
An array is created by initializing a variable which will be the name of the array together with
the new and Array keywords. When you create an array, you create a new instance of the Array
object. During the creation of array we can specify the size of array. The size is optional.

Array declaration with size:

[45]
Syntax:var arrayName = new Array([size]);

Example:

var arr1=new Array(5);

OR

var arr1;

arr1=new Array(5);

Array declaration without size:

Example: var arr1=new Array();

Creating an array this way, you can add as many values as you want to it. Alternatively, you can
specify an array to be of a particular size.

Index number of the array:The each element of the array can be indentified using index number.
The index number start from 0 and goes to size -1. If size of array is 5 then first index will be 0 and
last index will be 4 (5-1=4). The first index is called lower bound and last index is called upper bound.

Array definition (initialization):

We can access the array elements using their index number. Using index number we can access the
element to store the value into array and retrieve the value from array. The index number must be
writing inside square bracket.

Syntax:array_name[index_number]=value.

Example:
var arr1=new Array(5);

arr1[0]=34;

arr1[1]=4;

arr1[2]=3;

arr1[3]=5;

arr1[4]=7;

[46]
Accessing the value from Array:

Using index number we can retrieve the value from array. The index number must be writing inside
square bracket.

Syntax:variable=array_name[index_number]

Example:var x=arra[0];

Example:Store 5 values into array and print each value?


<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
var arr1=new Array(5);
arr1[0]=34;
arr1[1]=44;
arr1[2]=23;
arr1[3]=15;
arr1[4]=17;
document.write("Values of the array are: <br>");
var a,b,c,d,e;
a=arr1[0];
b=arr1[1];
c=arr1[2];
d=arr1[3];
e=arr1[4];
document.write("<br> arr1[0] : "+a);
document.write("<br> arr1[1] : "+b);
document.write("<br> arr1[2] : "+c);
document.write("<br> arr1[3] : "+d);
document.write("<br> arr1[4] : "+e);
</script>
</body>
</html>
Output:

[47]
Array declaration and definition (initialization) together
At the time of creation of array we can store the value into array.

Syntax:var arrayName = new Array(element 1, element 2, element n );


Example:
<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
var colors = new Array("green", "blue", "orange", "gray","lime");
document.write("Values of the array are: <br>");
var a,b,c,d,e;
a=colors[0];
b=colors[1];
c=colors[2];
d=colors[3];
e=colors[4];
document.write("<br> colors[0] : "+a);
document.write("<br> colors[1] : "+b);
document.write("<br> colors[2] : "+c);
document.write("<br> colors[3] : "+d);
document.write("<br> colors[4] : "+e);
</script>
</body>
</html>
Output:

Accessing the array values using loop:

We can access the value of the array using index number on the place of index number we can write
loop variable.

Example:
<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>

[48]
<body>
<script language="javascript" type="text/javascript">
var arr1 = new Array(45,34,23,87,11);

document.write("Values of the array are: <br>");


for(var i=0;i<=4;i++)
{
document.write("<br> arr1["+i+"] : "+arr1[i]);
}
</script>
</body>
</html>
Output:

Store the values into array from keyboard and accessing the array values:

Example:
<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
var arr1 = new Array(5);
document.write("Enter 5 values of the array <br>");
for(var i=0;i<=4;i++)
{
arr1[i]=eval(prompt("Enter the " +(i+1)+" element of array: "));
}
document.write("Values of the array are: <br>");
for(var i=0;i<=4;i++)
{
document.write("<br> arr1["+i+"] : "+arr1[i]);
}
</script>
</body>
</html>
Output:

[49]
Print addition of all elements of the array?

Example:
<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
var arr1 = new Array(5);
var x=0;
document.write("Enter 5 values of the array <br>");
for(var i=0;i<=4;i++)
{
arr1[i]=eval(prompt("Enter the " +(i+1)+" element of array: "));
}

for(var i=0;i<=4;i++)
{
x=x+arr1[i];
}
document.write("<br>Additin of all elements of array is : "+x);
</script>
</body>
</html>
Output:

 Function in JavaScript
A function is a segment of code grouped into a single entity. The great thing about functions is that
you can re-use them. By doing so, you eliminate the need to re-type the same code over and over
again. Once you implement a function, you can use its code by calling that function.It can be call
again and again.

[50]
You can pass data, known as parameters, into a function. Functions are used to perform certain
actions, and they are important for reusing code: Define the code once, and use it many times.

There are two type of function.

(1) Pre-defined function.

(2) User defined function.

(1) Pre-defined function:


It is a built-in function. It can be used by their name.

Example: write(), eval(), typeof() and parseInt() functions etc.

(2) User defined function.


To performs the specific task used can defined the own function. The function name should be in
lower case as identifier rules. If two words uses into the function name then first character of second
word must be in upper case.

On the basis of requirement there are four ways to create the function.

(1) Not takes arguments and not returns value function.


(2)Takes arguments and not returns value function.
(3) Not takes arguments and returns value function.
(4)Takes arguments and returns value function.

(1) Not takes arguments and not returns value function


This function does not take any argument and does not return the value. Into the javascript the function
has two parts.

(a) Function definition.


(b) Function calling.

(a) Function definition:

The function can be defined either inside <head> or <body>area in <script> tag.To create a function,
use the function keyword, followed by the function name, followed by parentheses, followed by an
opening brace and a closing brace. The lines of code which make up the function will go in between
the braces.

Syntax:
<script language="javascript" type="text/javascript">
function function_name()
{

Lines of codes;

}
</script>
[51]
Example:
<script language="javascript" type="text/javascript">
function add()
{
var a,b;
a=5;
b=9;
c=a+b;
document.write("<br>Addition (a+b): "+(a+b));

}
</script>

(b) Function calling:

The function can be called by their names. The function can be called any number of times.
The function can be call either inside <head>(if defined function in head) or <body>(if defined
function in head of body) area in <script> tag. But if function defines inside body then cannot be call it
from <head> tag.

Syntax:
<script language="javascript" type="text/javascript">
function_name();
</script>

Example:

<script language="javascript" type="text/javascript">


add();
</script>

Example 1: Addition of two numbers?


<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
<script language="javascript" type="text/javascript">
function add()
{
var a,b;
a=5;
b=9;
c=a+b;
document.write("<br>Addition (a+b): "+(a+b));
}
</script>

[52]
</head>
<body>
<script language="javascript" type="text/javascript">
add();
</script>
</body>
</html>
Output:

Example 2: Takes two numbers from keyboard and print their addition?
<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<script language="javascript" type="text/javascript">
function add()
{
var a,b,c;
a=eval(prompt("Enter first number : "));
b=eval(prompt("Enter second number : "));
document.write("<br>First number: "+a);
document.write("<br>Second number: "+b);
document.write("<br>Addition (a+b): "+(a+b));
}
add();
</script>
</body>
</html>
Output:

Note:
Function can be defined and call in one tag either in <head> tag or in <body> tag.

It function will be defined in <head> tag then can be call either in <head> tag or in <body> tag.
[53]
It function will be defined in <body> tag then can be call only in <body> tag.

(2) Takes arguments and not returns value function

This function takes any argument and does not return the value. Into the javascript the function has
two parts.

(a) Function definition.


(b) Function calling.

(a) Function definition:

This function takes argument, then to receive the argument the parameters will be used at the line of
definition of the function.

Syntax:
<script language="javascript" type="text/javascript">
function function_name(parameter 1, parameter 2, parameter n)
{

Lines of codes;

}
</script>

Example:
<script language="javascript" type="text/javascript">
function add(a,b)
{
c=a+b;
document.write("<br>Addition (a+b): "+(a+b));

}
</script>

(b) Function calling:


At the time of function calling, the argument will be pass into the fynction.
Syntax:
<script language="javascript" type="text/javascript">
function_name(argument 1, argument 2, argument n);
</script>

Example:

<script language="javascript" type="text/javascript">

[54]
add(5,6);
</script>

Example: Add two numbers which will be passing from the calling place into function?
<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
<script language="javascript" type="text/javascript">
function add(a,b)
{
var c;
document.write("<br>First number: "+a);
document.write("<br>Second number: "+b);
document.write("<br>Addition (a+b): "+(a+b));
}
</script>
</head>
<body>
<script language="javascript" type="text/javascript">
add(8,9);
</script>
</body>
</html>
Output:

(3) Not takes arguments and returns value function.

This function does not take any argument and return the value from function. Into the javascript the
function has two parts.

(a) Function definition.


(b) Function calling.

(a) Function definition:

This function return the value from function, so return keyword will be use into function for return
the value. Returning value will be received by the calling place of the function.

Syntax:
<script language="javascript" type="text/javascript">

[55]
function function_name()
{

Lines of codes;

return(values);
}
</script>

Example:
<script language="javascript" type="text/javascript">
function add()
{
var a,b,c;
a=8,b=7;
c=a+b;
return(c);
}
</script>

(b) Function calling:


At the time of function calling the returning value can be hold into the variable.
Syntax:
<script language="javascript" type="text/javascript">
variable=function_name();
</script>

Example:

<script language="javascript" type="text/javascript">


var x=add();
document.write("<br>Addition (a+b): "+x);
</script>

Example:
<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
<script language="javascript" type="text/javascript">
function add()
{
var a,b,c;
a=8,b=7;
c=a+b;
return(c);

[56]
}
</script>
</head>
<body>
<script language="javascript" type="text/javascript">
var x=add();
document.write("<br>Addition (a+b): "+x);
</script>
</body>
</html>
Output:

(4) Takes arguments and returns value function.

This function takes any argumentand returns the value from function.

Example:
<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
<script language="javascript" type="text/javascript">
function add(a,b)
{
var c;
c=a+b;
return(c);
}
</script>
</head>
<body>
<script language="javascript" type="text/javascript">
var x=add(5,7);
document.write("<br>Addition (a+b): "+x);
</script>
</body>
</html
Output:

[57]
 value property
The value property sets or returns (access) the value of the text field (textbox) using their id.
This method provides the value in string format so must be converting that value into number format
for performs the mathematical operations.

onclick event: This is a event of mouse click and action will be performs when click on the button. So
this even must be add with button input element and specify method name which will be call when
click on the button.

Syntax: variable= document.getElementById("html element id").value;

Example: Takes the number form textbox and print their addition?
<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
Enter first number: &nbsp &nbsp &nbsp &nbsp &nbsp
<input type="text" id="t1"/><br><br>
Enter second number: &nbsp &nbsp &nbsp
<input type="text" id="t2"/><br><br>
Press button for addition:
<input type="button" id="b1" value="ADD" onclick="add()"/>
<script language="javascript" type="text/javascript">
function add()
{
var a,b,x,y,c;
a=document.getElementById("t1").value;
b=document.getElementById("t2").value;
document.write("<br>Type of a is: "+typeof(a));
document.write("<br>Type of b is: "+typeof(b));
x=eval(a);
y=eval(b);
c=x+y;
document.write("<br><br>Addition (a+b): "+c);
}
</script>
</body>
</html>
Output:

[58]

 forms method with value method


This method is used to access the value from the form element (like textbox). It is a form element
method and must be used with document command using dot (.) sign. This method provides the value
in string format so must be converting that value into number format for performs the mathematical
operations.

Syntax: variable=document.forms[“form_name”][“textbox_name”].value;

Example: Takes the number form textbox and print there addition?
<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
<form name="myform">
Enter first number: &nbsp &nbsp &nbsp &nbsp &nbsp
<input type="text" id="t1"/><br><br>
Enter second number: &nbsp &nbsp &nbsp
<input type="text" id="t2"/><br><br>
Press button for addition:
<input type="button" id="b1" value="ADD" onclick="add()"/>
</form>
<script language="javascript" type="text/javascript">
function add()
{
var a,b,x,y,c;
a=document.forms["myform"]["t1"].value;
b=document.forms["myform"]["t2"].value;
document.write("<br>Type of a is: "+typeof(a));
document.write("<br>Type of b is: "+typeof(b));
x=eval(a);
y=eval(b);
c=x+y;
document.write("<br><br>Addition (a+b): "+c);
}
</script>
</body>
</html>

[59]
Output:

 value property with id of input element


The value method also used to access the value from the textbox using their id.

Syntax: variable=textbox_id.value;

Example: variable=t1.value;

onchange event: It is a event of textbox input element and performs the action when value of the
textbox will be changed from previous value. This event must be writing with textbox input element
and specify the function name which will be called when change the value of textbox.

Example: Takes the number form textbox and print that number?
<!doctype html>
<html>
<head><meta charset="utf-8">
<title>CAREER TECH ACADEMY</title>
</head>
<body>
Enter any number:
<input type="text" id="t1" onchange="prime()"/><br>
<script language="javascript" type="text/javascript">
function prime()
{
var n,f,c=0,i=1;
n=t1.value;
document.write("Type of value is: "+typeof(n));

document.write("<br><br>The given number is : "+n);


}
</script>
</body>
</html>
Output:

Then click on out of textbox then generate following output.

[60]
JavaScript Events
 What is event in JavaScript:
The change in the state of an object is known as an Event. An event is an action that occurs as per the
user's ineraction.

Events are a part of the DOM (Document Object Model) Level 3 and every HTML element contains a
set of events which can trigger JavaScript Code.

 Handled the event in JavaScript:


The process of reacting over the events is called Event Handling. The javascript handles the HTML
events via HTMLEvent Handlers.

 Even types

There are following HTML events and their HTML event handlers are:
(1) Mouse events:
Event name Event Description
Handler
click onclick When mouse click on an element
mouseover onmouseover When the cursor of the mouse comes over the element
mouseout onmouseout When the cursor of the mouse leaves (remove) an element
mousedown onmousedown When the mouse button is trying to pressed over the element
mouseup onmouseup When the mouse button is released over the element
mousemove onmousemove When the mouse movement takes place.
(2) Keyboard events:
Event name Event Handler Description
Keydown onkeydown When the user press the key
Keyup onkeyup When the user release the key

(3) Form events:


Event name Event Description
Handler

focus onfocus When the user focuses on an element


submit onsubmit When the user submits the form
blur onblur When the focus is away from a form element
change onchange When the user modifies or changes the value of a form
element
(4) Window/Document events
Event name Event Description
[61]
Handler
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the
browser unloads it
resize onresize When the visitor resizes the window of the browser

(1) Mouse events:


It is a mouse input device-related event. This event will be generated when a mouse-related operation
(change the state of mouse) performs by the user. After generating the event the event handler will
handle the event.In event handling process we can execute any block of code to perform specific tasks
like functions.

There are following mouse related events and their event handlers are:

(1) Mouse events:


Event Name Event Handler Description

click onclick When mouse click on an element.


mouseover onmouseover When the cursor of the mouse comes over the element.
mouseout onmouseout When the cursor of the mouse leaves an element.
mousedown onmousedown When the mouse button is trying to pressed over the element.
mouseup onmouseup When the mouse button is released over the element.
mousemove onmousemove When the mouse movement takes place.

(a) Click event:

This event will be generates when user clicked on the HTML object (element) by mouse. To handle
of this event the onclick event handler will be used.

The event handler will be added to that element who element will generate the event. The event
handler will be write in HTML tag as attribute, related to the HTML tag event.

Syntax:
With single quotes: <tag event_ handler_ name='JavaScript Code'>

With double quotes: <tag event_ handler_ name= “JavaScript Code”>


Example:

<input type="button" onclick="clickevent()" value="Who's this?"/>

Example: Click on button then print institute name?


<!doctype html>
<html>
<head>
<meta charset="utf-8"/>

[62]
<title> CAREER TECH ACADEMY </title>
</head>
<body bgcolor="silver">
<script language="Javascript" type="text/Javascript">
function clickevent()
{
document.write("CAREER TECH ACADEMY");
}
</script>
<form>
<input type="button" onclick="clickevent()" value="Click Here"/>
</form>
</body>
</html>
Output:

 value property

The value property sets or returns (access) the value of the text field (textbox) using their id.
This method provides the value in string format so must be converting that value into number format
for performs the mathematical operations.

Syntax: variable= text_box_id.value;

Example: Takes two numbers from keyboard and print +,-,* and / operation?
<html>
<head>
<title>O level</title>
</head>
<body>
Enter first number : <input type="text" id="t1"/> <br>
Enter second number : <input type="text" id="t2"/> <br>
Press button:<br>
<input type="button" id="b1" value="+" onclick="add();"/>
<input type="button" id="b2" value="-" onclick="sub();" /> <input type="button"
id="b3" value="*" onclick="mul();"/> <input type="button" id="b1" value="/"
onclick="div();"/> <br>
<script>
function add()
{
var a=eval(t1.value); var b=eval(t2.value);
alert("Addition is : "+(a+b));
}
function sub()
{
[63]
var a=eval(t1.value); var b=eval(t2.value);
alert("Subtraction is : "+(a-b));
}
function mul()
{
var a=eval(t1.value); var b=eval(t2.value);
alert("Multiplication is : "+(a*b));
}
function div()
{
var a=eval(t1.value); var b=eval(t2.value);
alert("Division is : "+(a/b));
}
</script>
</body>
</html>
OUTPUT

(b) Mouse over event


This event will be generates when user hover the mouse on the HTML object (element). To handle of
this event the onmouseoverevent handler will be used.

Example:The mouse hover on the paragraph then display the message?


<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<script language="Javascript" type="text/Javascript">
function mouseoverevent()
{
alert("This is javascript event");
}
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>
Output:

[64]
(c) Mouse outevent
This event will be generates when the mouse pointer is moved out of an element (cursor away from
element). To handle of this event the onmouseout handler will be used.
Example:The moved outof mouse then displays the message?
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<script language="Javascript" type="text/Javascript">
function mouseoverevent()
{
alert("This is javascript event");
}
</script>
<p onmouseout="mouseoverevent()"> Keep cursor over me again</p>
</body>
</html>
Output:

(d) Mouse downevent


This event will be generates when the click the mouse on html element (object). To handle of this
event the onmousedownhandler will be used.

Example:Click on object then displays the message?


<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
</head>
<body>

[65]
<script language="Javascript" type="text/Javascript">
function mouseoverevent()
{
alert("This is javascript onmousedown event handler ");
}
</script>
<p onmousedown="mouseoverevent()"> Click over me again</p>
</body>
</html>
Output:

(e) Mouseup event


This event will be generates when the click the mouse (leave the mouse click after click) on html
element (object). To handle of this event the onmousedownhandler will be used.

Example:Click on object and leave the mouse key it then displays the message?
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<script language="Javascript" type="text/Javascript">
function mouseoverevent()
{
alert("This is javascript onmouseup event handler ");
}
</script>
<p onmouseup="mouseoverevent()"> Click over me again</p>
</body>
</html>
Output:

[66]
(f) MouseMove Event
This event will be generates when the move the mouse over html element (object). To handle of this
event the onmousemovehandler will be used.
Example:Move the mouse on object then displays the message?
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<script language="Javascript" type="text/Javascript">
function mouseoverevent()
{
alert("This is javascript onmousemove event handler ");
}
</script>
<p onmousemove="mouseoverevent()"> Move the mouse over me again</p>
</body>
</html>
Output:

(2) Keyboard events:


It is a keyboard input device-related event. This event will be generated when a keyboard-related
operation performs by the user. After generating the event the event handler will handle the event.In
event handling process we can execute any block of code to perform specific tasks like functions.

There are following keyboard related events and their event handlers are:

(2) Keyboard events:


Event Event Handler Description
Performed

Keydown onkeydown When the user press the key.

[67]
Keyup onkeyup When the user release the key.

(a) Keydown Event


This event will be generates when the press any key into textbox to writing the text. To handle of this
event the onkeydownhandler will be used.
Example: If type anything then display the message?
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keyboardevent()"/>
<script>
function keyboardevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
</script>
</body>
</html>
Output:

(b) KeyupEvent

This event will be generates when release the key after typed into textbox. To handle of this event the
onkeyup handler will be used.

Example: When release the key after typed then display the message?
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeyup="keyboardevent()"/>
<script>
[68]
function keyboardevent()
{
alert("Pressed a key");
}
</script>
</body>
</html>
Output:

(3) Form events:


It is input form related event. This event will be generated when a form elements related operation
performs by the user. After generating the event the event handler will handle the event. In event
handling process we can execute any block of code to perform specific tasks like functions.

There are following form related events and their event handlers are:

(3) Form events:


Event Event Description
Performed Handler

focus onfocus When the user focuses on an element.


submit onsubmit When the user submits the form.
blur onblur When the focus is away from a form element.
change onchange When the user modifies or changes the value of a form
element.

(a) Focus Event


This event will be generates when try to write into textbox. To handle of this event the onfocushandler
will be used.

Example: When try to write into textbox then generates event to display box?
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<form>
[69]
<h2> Write something here</h2>
<input type="text" id="input1" onfocus="formevent()"/>
</form>
<script>
function formevent()
{
alert("Try to write something in textbox: ");
}
</script>
</body>
</html>
Output:

(b) Submit Event

This event will be generates when click on submit button of form. To handle of this event the
onsubmithandler will be used. The action attribute must be apply into form tag. This even handler
will be add into <form> tag.

Example:If click on submit button then generates the event?


<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<p>When you submit the form, a function is triggered which alerts some
text.</p>
<form action="/action_page.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>

[70]
Output:

(c) blur (कलंक)Event


It work as:When you leave the input field, a function is triggered which transforms the input text to
upper case.
<!DOCTYPE html>
<html>
<body>
Enter your name: <input type="text" id="fname" onblur="myFunction()">

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

<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>
Output

(d) Onchange Event


It works when change the item by selecting on list.

<!DOCTYPE html>
<html>
<body>
<p>Select a new car from the list.</p>
<select id="mySelect" onchange="myFunction()">
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes">Mercedes</option>
<option value="Volvo">Volvo</option>
</select>
[71]
<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>

<p id="demo"></p>

<script>
function myFunction() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
</script>

</body>
</html>
Output

(4) Window/Document events:


It is web page (window) related event. This event will be generated when a web page will be load.
After generating the event the event handler will handle the event. In event handling process we can
execute any block of code to perform specific tasks like functions.

There are following web page (window) related events and their event handlers are:

(4) Window/Document events


Event Event Description
Performed Handler

load onload When the browser finishes the loading of the page.
unload onunload When the visitor leaves the current webpage, the browser unloads
it.
resize onresize When the visitor resizes the window of the browser.

(a) Load Event


This event will be generates when web page will be load. To handle of this event the onload handler
will be used. This even handler will be add into <body> tag.
Example:If page will be load then generate the event?
<!doctype html>
<html>
<head>

[72]
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
</head>
<body onload="myFunction()">
<h1>Window load even</h1>
<script>
function myFunction()
{
alert("The page is loaded successfully");
}
</script>
</body>
</html>
Output:

(b) unload Event


It works when page will not be load (run).
<!DOCTYPE html>
<html>
<body onunload="myFunction()">
<h1>Welcome to my Home Page</h1>
<p>Close this window or press F5 to reload the page.</p>
<p><strong>Note:</strong> Due to different browser settings, this event may not always work as
expected.</p>
<script>
function myFunction() {
alert("Thank you for visiting W3Schools!");
}
</script>
</body>
</html>
Output

(c) resize Event


It works when browser window will be resized by mouse, like normal window.
<!DOCTYPE html>
<html>
[73]
<body onresize="myFunction()">
<p>This example demonstrates how to assign an "onresize" event to a body element.</p>
<p>Try to resize the browser window.</p>
<p>Window resized <span id="demo">0</span> times.</p>
<script>
var x = 0;
function myFunction() {
var txt = x += 1;
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
Output

Basic Form Validations in JavaScript


The form is used to capture the data by client or user. JavaScript provides a way to validate form's data
on the client's computer before sending it to the web server. Form validation generally performs two
functions.

(1) Basic Validation: First of all, the form must be checked to make sure all the mandatory
fields are filled in. It would require just a loop through each field in the form and check for data.

(2) Data Format Validation: Secondly, the data that is entered must be checked for correct
form and value. Your code must include appropriate logic to test correctness of data.

Example 1:Check that user has enter the name or not?


<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
</head>
<script>
function validateForm()
{
var x=t1.value;

[74]
if (x=="")
{
alert("Name must be filled out");
}
else
{
document.write("Given name: "+x);
}
}
</script>
</head>
<body>
<h2>JavaScript Validation</h2>
<form name="myForm" action="/action_page.php" method="post">
Enter Name: <input type="text" name="fname" id="t1">
<input type="submit" value="SUBMIT" onclick="validateForm()">
</form>
</body>
</html>
Output:

Example 2:Check that user input numeric or alphabetic value?


<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
</head>
<body>
<h2>JavaScript Validation</h2>
<p>Please input a number only:</p>
<input type="text" id="numb">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction()
{
let x = document.getElementById("numb").value;
let text;
if(isNaN(x)==false)
[75]
{
text = "Input OK";
}
else
{
text = "Input not OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
Output:

Example: Enter name and password and check valid or not? (GOOD)

<html><head><title>web page</title></head>
<body>
<form name="frm1">
Enter your name:&nbsp &nbsp &nbsp <input type="text" id="t1"/><br>
Enter your password:<input type="text" id="t2"/><br><br>
Press for login :&nbsp <input type="button" value="LOGIN" onclick="show();">
</form>
<script>
function show()
{
var name="rajesh kumar"; var pwd=123; var n,p;
n=t1.value; p=eval(t2.value);
if(name==n)
document.write("Your name is correct : "+n);
else
document.write("Your name is not correct : "+n);
if(pwd==p)
document.write("<br>Your password is correct : "+p);
else
document.write("<br>Your password is not correct : "+p);
}

[76]
</script>
</body>
</html>
Output

Example: Enter name and password and if valid then do login otherwise nothing?
(GOOD)
<html><head><title>web page</title></head>
<body>
<form name="frm1">
Enter your name:&nbsp &nbsp &nbsp <input type="text" id="t1"/><br>
Enter your password:<input type="text" id="t2"/><br><br>
Press for login :&nbsp <input type="button" value="LOGIN" onclick="show();">
</form>
<script>
function show()
{
var name="rajesh kumar"; var pwd=123; var n,p;
n=t1.value; p=eval(t2.value);
if(name==n)
document.write("Your name is correct : "+n);
else
return false; // no response
if(pwd==p)
document.write("<br>Your password is correct : "+p);
else
return false; // no response
if(name==n && pwd==p)
{
document.write("<br><a href='log.html'>LOGIN</a> ")
}
}
</script>
</body>
</html>

[77]
Introduction to Angular JS: Expressions, Modules and Directives

AngularJS was a JavaScript-based open-source and free front-end web framework for developing SPA
(Single Pageweb Applications). AngularJS is a structural framework for dynamic web apps. It is a
library written in javascript.

It was originally developed in 2009 by Misko Hevery and Adam Abrons. It is now maintained by
Google. Its latest version is 1.2.21.

It lets you use HTML as your template language and lets you extend HTML's syntax to express your
application components clearly and succinctly. Its data binding and dependency injection eliminate
much of the code you currently have to write. And it all happens within the browser, making it an
ideal partner with any server technology.

AngularJS is a framework to build large scale, high-performance, and easyto-maintain web


applications.

AngularJS base on MVVM (Model-View-ViewModel) Architectural pattern and used for SPA
(Single Page Application).

 General Features:
The general features of AngularJS are as follows −
• AngularJS is efficient framework that can create Rich Internet Applications (RIA).

• AngularJS provides developers an options to write client side applications using JavaScript in a
clean Model View Controller (MVC) way.

• Applications written in AngularJS are cross-browser compliant. AngularJS automatically


handles JavaScript code suitable for each browser.

• It is licensed under the Apache license version 2.0.

 Core Features
The core features of AngularJS are as follows:
Data-binding: It is the automatic synchronization of data between model and view components.
Scope: These are objects that refer to the model. They act as a glue between controller and view.
Controller: These are JavaScript functions bound to a particular scope.
Services: AngularJS comes with several built-in services such as $http to make a XMLHttpRequests.
These are singleton objects which are instantiated only once in app.
[78]
Filters: These select a subset of items from an array and returns a new array.

Directives: Directives are markers on DOM (Document Object Model)elements such as elements,
attributes, css, and more. These can be used to create custom HTML tags that serve as new, custom
widgets. AngularJS has built-in directives such as ngBind, ngModel, etc.

Templates: These are the rendered view with information from the controller and model. These can
be a single file (such as index.html) or multiple views in one page using partials.

Appling AngularJS with HTML Code


We can include the angular JS into html program by the following two ways.

(1) Using angular JS URL:


If Internet connections are available all time then wecan include the angular JS code into html program
using angular JS code URL.

The URL is http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js

This URL must be writing into src attribute of <script> tag in side<head> tag (not in <body>) tag.

Example:

<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
</head>

(2) Using angular JS File:


There are following steps to include the JS file into HTML code.

Step 1:First of all write the following URL into address bar of browser.

The URL is http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js

Step 2:Then open angular JS code file. Then save (press CTRL+S) that code into notepad++ file with
filename and .js extension (as: cta.js).

Step 3:Then includes cta.jsangularjs fileinto HTML program file. We can include cta.jsangularjs
fileusing src attributes of <script> tag inside <head> tag.

Example:

<!doctype html>
<html>
<head>

[79]
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
<script src="cta.js"></script>
</head>
Note: We can include the angularjs file either inside <head> tag or inside <body> tag (at starting
position) into HTML program file.

AngularJS Including
HOW CAN INCLUDES ANGULAR JS IN HTML FILE
To include the angular JS into html program, there are following two ways.
(1) One Way
If Internet connections are available all time then wecan include the angular JS code into html program
using angular JS code URL.
The URL is ("http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"). This URL must be
write into src attribute of <script> tag in side<head> tag. (not in <body>) tag.

As:

<head><title> app file</title>


<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
(2) Two Way
Step 1: Write the https://angularjs.org/, URL (for AngularJS v1.8.2) in web browser then open a
window as follows.

Step 2: Then click on DOWNLOAD ANGULARJS button. Then open another window as follows.

This screen gives various options of using Angular JS as follows −

• Downloading and hosting files locally: select 1.8.x in Branch, Minified in


Build.
o There are two different options : Legacy and Latest. The names

[80]
themselves are self-descriptive. The Legacy has version less than 1.2.x
and the Latest come with version 1.3.x.
o We can also go with the minimized, uncompressed, or zipped version.
• CDN (Content Delivery Network) access − You also have access to a CDN.
The CDN gives you access to regional data centers. In this case, the Google host.
The CDN transfers the responsibility of hosting files from your own servers to a
series of external ones. It also offers an advantage that if the visitor of your web
page has already downloaded a copy of AngularJS from the same CDN, there is
no need to re-download it.
Step 3: Then click on download button. OR write the url
(“https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js”) into web browser to save the
AngularJS v1.6.9.

Step 4:Then open angular JS code file. Then save that code (CTRL+S) into the notepad++ at html file
location with file_name (file_name can be anything) and .js extension. As:angular.js

Step 5:In HTML program file we can includes the angular.jsfile using src attributes of <script> tag
inside <head> or <body> (in <body> tag at starting position) tag.

Ex:<head><title> JS Application</title><script src="angular.js"></script></head>

 AngularJS Directives
########################################################################

AngularJS Directives

The prefix ng stands for ‘Angular’.All of the built-in directives of Angular use thengprefix. Similarly,
it is recommended that you do not use the ng prefix on your own directives in order to avoid possible
name collisions in future versions of Angular.

AngularJS facilitates you to extend HTML with new attributes. These attributes are called
directives.Directives are special attributes starting with ngprefix.

There are two types of AngularJS directives.

(a)Built-in directives.
(b)Custom directives (User defined).

a) Built-in directives
It special directives and start with ng prefix. It is html attributes. There are following directives of
AngularJS framework:

[81]
(1) ng-app directive.
(2) ng-initdirective.
(3) ng-model directive.
(4) ng-binddirective.
(5) ng-repeat directive.
(6) ng-click directive.
(7) ng-src directive.
(8) ng-controller directive

(1) ng-app directive:


This directive indicates the starting (initialize) an AngularJS Application and links anAngularJS
application to HTML. It tellsthat which part of HTML contains the AngularJS app. So to use angular
JS must be use ng-app in html element.

The ng-app directive in AngularJS is used to define the root element of an AngularJS application.

It can be used to load various modules in AngularJS Application.

The ng-app directive tells AngularJS that the <html>, <body> or <div> tagare the "owner" of an
AngularJS application.

This directive automatically initializes the AngularJS application on page load.It checked that which
part of the html element contains the ng-app directives.

 Uses of ng-app directive:


We can use it in root <html>, <body> or <div> tag.Its scope is limited inside of the open and close
html element. (<html> or <body> or <div>).

Syntax:

<html_element ng-app="modulename"> Contents... </html_element>

None: Modulename isOptional. It specifies the name of a module to load into theapplication (html
page). [Example  At the last]

[82]
 Creating AngularJS Application [[ Demo Example ]]
Step 1: Load framework

Being a pure JavaScript framework, it can be added using <Script> tag.


<script
src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
Step 2: Define AngularJS application using ng-app directive
<div ng-app = "">
...
</div>
Step 3: Define a model name using ng-model directive
<p>Enter your Name: <input type = "text" ng-model = "name"></p>

Step 4: Bind the value of above model defined using ng-bind directive

<p>Hello <span ng-bind = "name"></span>!</p>

Executing AngularJS Application


testAngularJS.htm

<html>
<head>
<title>AngularJS First Application</title>
</head>
<body>
<h1>Sample Application</h1>

<divng-app="">
<p>Enter your Name: <inputtype="text"ng-model="name"></p>
<p>Hello <spanng-bind="name"></span>!</p>
</div>

<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</body> [83]
</html>
Output
Print Data using HTML_element with the help of angular JS
We can print data with the help of angularJS wing html_element . The data or variable will be writing
within double quote marks. The string value will be writing within either single quote (,) mark [If
double quote mark (“ ”)uses in html] or double mark (“”) mark [If single quote mark (‘’)uses in html].
To concatenate the string message and variable the + sign will be used.
The quote marks must be different of inside from outside. If outer quote marks is single (‘’) then inner
quote marks will be double (“”).
Syntax:
<HTML_tag> contents: {{ data or variable [< operator >]data or variable }}</HTML_tag>

Example 1:Add two numbers, and print result ? [printing the value]

<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body>
<div ng-app="">
<p>My first expression: {{5+5}}</p>
</div>
</body>
</html>
OR
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
<script src="cta.js"></script>

[84]
</head>
<body>
<div ng-app="">
<p>My first expression: {{5+5}}</p>
</div>
</body>
</html>
Output:

Example: Printing the message?


<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body>
<div ng-app="">
<p>My first expression: </p>
<p>{{'My angular JS'}}</p>
<p>{{"My angular JS"}}</p>
</div>
</body>
</html>
Output:

Example: Printing the message and value?


<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body>
<div ng-app="">
<p>My first expression: </p>
<p>{{'First number: '+5}}</p>

[85]
<p>{{'Second number: '+7}}</p>
<p>{{'Addition is : '+(5+7)}}</p>
</div>
</body>
</html>
Output:

(2) ng-init directive


The ng-init directive initializes an AngularJS Application data. It is used to assign values to the
variables. String value must be in single quote mark. It must be define after ng-app directives at the
same html element. Its value can be print only by expression.

Here can define dictionary like Python.

Syntax:

<html_element ng-app="modulename" ng-init=“variable1=value1; variable2=value2;


variable_n=value_n;” >

Contents...

</html_element>

Example 1:Print Name and rollnumber?


<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
<script src="cta.js"></script>
</head>
<body>
<div ng-app="" ng-init="name='Rajesh kumar';roll=100;">
<p>My first expression:<br>{{'Name is:'+name + "Roll number is:"+roll}}</p>

<p>My first expression:<br>{{'Name is:'+name}}<br> {{"Roll number is:"+roll}}</p>

</div>
</body>

[86]
</html>
Output:

Example 2:Print single string?


<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
<script src="cta.js"></script>
</head>
<body>
<h2>ng-app directive</h2>
<div ng-app="" ng-init="name='GeeksforGeeks'">
<p>{{ name }} is the name of portal</p>
</div>
</body>
</html>
Output:

 In ng-init directivecan use as dictionary (like Python).


To access the value we can use dir-name and attribute with . (dot) sign.

Example 1:
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
<script src="cta.js"></script>
</head>
<body>
<div ng-app="" ng-init="info='Student information';">

[87]
{{info}}

<div ng-app="" ng-init="name={fname:'rajesh'};roll=100;">


Name is: {{name.fname}}<br>
Rollnumber is:{{roll}}
</div>
</div>
</body>
</html>
Output:

Example 2:
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
<script src="cta.js"></script>
</head>
<body>
<div ng-app="" ng-init="name={fname:'rajesh',lname:'kumar'}">
Name is: {{name.fname+" "+name.lname}}
</div>
</body>
</html>
Output:

(3) ng-model directive


This directive binds the values of AngularJS application with HTML input controls. (It binds the value
of HTML controls to application data). The input controls can be input (text, checkbox, radio, number,
email, url, date, datetime-local, time, month, week), select, textarea or custom form control.

This directive defines the model that is variable to be used in AngularJS. It is model variable.

The ng-model directive creates a model variable named name, which can be used with the HTML
page and within the div having ng-app directive.

 Into the ng-model directive we can pass model_name.


[88]
 We can pass variable_name_of ng-init directive to display the value of ng-init directive.

Note: It must be write inside input element of HTML tag.

Syntax: <input_html element ng-model="model_name or vaiable_name_of_ng-init"/>

Example 2:
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
<script src="cta.js"></script>
</head>
<body ng-app="" ng-init="Name='Dhirendra';Roll=100;">
Name is: <input type="text" ng-model="Name"/><br>
Rollnumber is: <input type="text" ng-model="Roll"/>
</body>
</html>
Output:

(4) ng-bind: This directive binds the AngularJS application data to HTML tags. It binds the
contents with output elements of html.

Note: It must be write inside output element of HTML tag (not in <p> tag).
 Into the ng-bind directive we can pass model_name.
 We can pass variable_name_of ng-init directive to display the value of ng-init directive.
Syntax:

<html_tag ng-bind="model_name (model_id) or variable of ng-init directive">


Contents...
</html_tag >

Example:
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title> CAREER TECH ACADEMY </title>
<script src="cta.js"></script>
</head>
<body ng-app="" ng-init="Name='Rajesh kumar';Roll=100;">
Name is:<h4 ng-bind="Name"></h4>

[89]
Rollnumber is:<h4 ng-bind="Roll"></h4>
</body>
</html>
Output:

As soon as writing then show in output


To show the output in <p> or <h1> as soon as type into textbox. The must be

 ng-model=”t1”  into textbox

 ng-bind=”t1”  into <p> or <h1>

Example 2: As soon as writing then show in output? GOOD EXAMPLE?

Using All directives: ng-app, ng-model and ng-bind

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="">

<p>Input something in the input box:</p>


<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>

</div>
</body>
</html>
Output

Example 2: As soon as type that reflect into output?


[90]
<html><head><title>AngularJS ng-app Directive</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
</head>
<body ng-app="">
<h1>GeeksforGeeks</h1>
<h2>ng-app Directive</h2>
<div>
<p>Name: <input type="text" ng-model="name"></p>
<p>You entered: <span ng-bind="name"></span></p>
</div>
</body>
</html>
Output

(5) ng-repeat directive


The ng-repeat directive repeats HTML elements for each item in a collection.

It is used to access the value using variable of ng-init directive. In this directive the in
operator is used like for loop of Python. It is work like for loop of Python. Basically is used for access
the value of sequence data like array. It can be writes into <li> tag of list.

Syntax:

<html_list ng-repeat=“variable in variable_name_of_ ng-init directive”>

{{ variable}}

</html_list>

Example 1: Good

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="" ng-init="arr=['Rajesh',100,78.5];">

[91]
<ol>
<li ng-repeat = "x in arr">
{{x}}
</li>
</ol>

</body>
</html>
Output

Example 2:In the following example, we iterate over the array of countries.

testAngularJS.htm
<html>
<head>
<title>AngularJS Directives</title>
</head>
<body>
<h1>Sample Application</h1>

<div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'},


{locale:'en-GB',name:'United Kingdom'}, {locale:'en-FR',name:'France'}]">
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
<p>Hello <span ng-bind = "name"></span>!</p>
<p>List of Countries with locale:</p>

<ol>
<li ng-repeat = "country in countries">
{{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
</li>
</ol>
</div>

<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">


</script>
</body>
</html>
Output
Sample Application

Enter your Name:


Hello !
List of Countries with locale:
1. Country: United States, Locale: en-US

[92]
2. Country: United Kingdom, Locale: en-GB
3. Country: France, Locale: en-FR

(6) ng-click directives

It performs the action when click on the object. It can be writes into output html tag like <li>, <p>,
<h1> etc.

Example 1:If click on 0 then increase the by 1?


<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="" ng-init="count=0;">
Click on the 0 to increase the value:
<p ng-click="count=count+1;">
{{count}}
</p>
</body>
</html>
Output

Example 2: If click on list of 0 then increase the by 1?

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="" ng-init="count=0;">
Click on the list of 0 to increase the value:
<ol>
<li ng-click="count=count+1;">
{{count}}
</li>
</ol>
</body>
</html>
Output

[93]
(7) ng-src directives

This directives is used to access the image to show using ng-init_variable. It can be writes
after ng-appdirective at the same place.
It has two steps:
Step 1: First of all define the image path in ng-init directive.

<body ng-app="" ng-init="img1='1.jpg';">

Step 2: Then write the ng-src directive.

Syntax:<img ng-src= “{{vaiable_name_of_ng-init_directive}}”/>

Example 1: Show the image?


<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="" ng-init="img1='1.jpg';">
This is a image:<br>
<img ng-src="{{img1}}"/>
</body>
</html>
Output

(8) ng-controller directives


This directive is used to specify the predefined controller. It adds a controller to your application. This
directive must be write after ng-app directive at the same line.
Syntax:
<tag ng-app=” ” ng-controller=” “> Text </tag>

(It described at the last, into module topic)

 List of all of AngularJS directives:


Directive Description
ng-app It defines the root element of an application.
ng-bind It binds the content of an html element to application data.
ng-bind-html Itbinds the innerhtml of an html element to application data, and also
[94]
removes dangerous code from the html string.
ng-bind- It specifies that the text content should be replaced with a template.
template
ng-blur It specifies a behavior on blur events.
ng-change It specifies an expression to evaluate when content is being changed
by the user.
ng-checked It specifies if an element is checked or not.
ng-class It specifies css classes on html elements.
ng-class-even It is same as ng-class, but will only take effect on even rows.
ng-class-odd It is same as ng-class, but will only take effect on odd rows.
ng-click It specifies an expression to evaluate when an element is being
clicked.
ng-cloak It prevents flickering when your application is being loaded.
ng-controller It defines the controller object for an application.
ng-copy It specifies a behavior on copy events.
ng-csp It changes the content security policy.
ng-cut It specifies a behavior on cut events.
ng-dblclick It specifies a behavior on double-click events.
ng-disabled It specifies if an element is disabled or not.
ng-focus It specifies a behavior on focus events.
ng-form It specifies an html form to inherit controls from.
ng-hide It hides or shows html elements.
ng-href It specifies a URL for the <a> element.
ng-if It removes the html element if a condition is false.
ng-include It includes html in an application.
ng-init It defines initial values for an application.
ng-jq It specifies that the application must use a library, like jQuery.
ng-keydown It specifies a behavior on keydown events.
ng-keypress It specifies a behavior on keypress events.
ng-keyup It specifies a behavior on keyup events.
ng-list It converts text into a list (array).
ng-model It binds the value of html controls to application data.
ng-model- It specifies how updates in the model are done.
options
ng-mousedown It specifies a behavior on mousedown events.
ng-mouseenter It specifies a behavior on mouseenter events.
ng-mouseleave It specifies a behavior on mouseleave events.
ng-mousemove It specifies a behavior on mousemove events.
ng-mouseover It specifies a behavior on mouseover events.
ng-mouseup It specifies a behavior on mouseup events.
ng-non- It specifies that no data binding can happen in this element, or it's
bindable children.
ng-open It specifies the open attribute of an element.
ng-options It specifies <options> in a <select> list.
ng-paste It specifies a behavior on paste events.
ng-pluralize It specifies a message to display according to en-us localization rules.
ng-readonly It specifies the readonly attribute of an element.
[95]
ng-repeat It defines a template for each data in a collection.
ng-required It specifies the required attribute of an element.
ng-selected It specifies the selected attribute of an element.
ng-show It shows or hides html elements.
ng-src It specifies the src attribute for the <img> element.
ng-srcset It specifies the srcset attribute for the <img> element.
ng-style It specifies the style attribute for an element.
ng-submit It specifies expressions to run on onsubmit events.
ng-switch It specifies a condition that will be used to show/hide child elements.
ng-transclude It specifies a point to insert transcluded elements.
ng-value It specifies the value of an input element.

Angular JS: Expressions


Expressions are used to bind application data to HTML. Expressions are written inside double curly
braces such as in {{ expression}}. We can write the message in single or double quote mark.
Between message and value + (plush) sign is used. Expressions behave similar to ng-bind
directives.AngularJS will "output" data exactly where the expression is written. AngularJS expressions
are pure JavaScript expressions and output the data where they are used.
The quote marks must be different of inside from outside. If outer quote marks is single (‘’) then inner
quote marks will be double (“”).

Using numbers
<p>Expense on Books : {{cost * quantity}} Rs</p>

Using Strings
<p>Hello {{student.firstname + " " + student.lastname}}!</p>

Using Object
<p>Roll No: {{student.rollno}}</p>

Using Array
<p>Marks(Math): {{marks[3]}}</p>

Example 1:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
</div>

</body>
</html>
[96]
Output
My first expression: 10

OR

<!DOCTYPE html>
<html>
<script src="angular.js"></script>
<body>
<div ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
</div>
</body>
</html>
Output
My first expression: 10

Example 2: (Good example)


<html>
<script src="angular.js"></script>
<body>
<div ng-app="" ng-init="name='Rajesh kumar';roll=100;">
<p>My first expression:<br> {{ 'Name is:'+name + " Roll number is:"+roll }}</p>
</div>
</body>
</html>
Output
My first expression:
Name is:Rajesh kumar Roll number is:100

Example 3:testAngularJS.htm
<html>
<head>
<title>AngularJS Expressions</title>
</head>
<body>
<h1>Sample Application</h1>

<div ng-app = "" ng-init = "quantity = 1;cost = 30;


student = {firstname:'Mahesh',lastname:'Parashar',rollno:101};
marks = [80,90,75,73,60]">
<p>Hello {{student.firstname + " " + student.lastname}}!</p>
<p>Expense on Books : {{cost * quantity}} Rs</p>
<p>Roll No: {{student.rollno}}</p>
<p>Marks(Math): {{marks[3]}}</p>
</div>

<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">


[97]
</script>

</body>
</html>
Output
Sample Application

Hello Mahesh Parashar!


Expense on Books : 30 Rs
Roll No: 101
Marks(Math): 73
Example 4:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="">

<p>Input something in the input box:</p>


<p>Name: <input type="text" ng-model="name"></p>
<p>{{name}}</p>

</div>

</body>
</html>
Output
Input something in the input box:
Rajesh
Name:
Rajesh
 In express we can use the dictionary like Python.
To access the value we can use dir-name and attribute with . (dot) sign.

Syntax:
<HTML_tag> {{dir-name.attribute}} </ HTML_tag >

Example 1:
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="" ng-init="name={fname:'rajesh'}">


Name is: {{name.fname}}

</div>

[98]
</body>
</html>

Output

Name is: rajesh

Example 2:
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="" ng-init="name={fname:'rajesh',lname:'kumar'}">


Name is: {{name.fname+" "+name.lname}}
</div>

</body>
</html>
Output

Name is: rajesh kumar

 Introduction to Angular JS: Modules (ng-app=”module_name”)

AngularJS supports modular approach. Modules are used to separate logic such as services,
controllers, application etc. from the code and maintain the code clean. We define modules in
separate js files and name them as per the module.js file.

In AngularJS, a module defines an application. It is a container for the different parts of your
application like controller, services, filters, directives etc.

Creation of module in three parts (steps)


To create the module we can understands of the following three components.
(1) App (view).
(2) Module
(3) Controller

(1) App (view): It is html code and used to provides the elements to the output. In this part the
ng-app directive must be write. (after ng-app directive will be write ng-controller at the same
line).

[99]
(2) Module: It is a java script code and must be write inside <script></script> tag. In this part
defines the module.

(3) Controller:It is a java script code and must be write inside <script></script> tag. In this
part defines the controller.

 Steps to creates the module

(Step 1): Creation of module.

A module is used as a Main() method.The angular object's module() method is used to create a
module. It is also called AngularJS function angular.module.

[[If creates the module into html file then it must that module code write inside <script></script> tag
before the closing </body> tag. ]]

To create the module module() method is used with angular object as angular.module().

 At the time of creation of module must be pass following two parameters.


(i) The first is module_name can be anything. This module_name has been written in ng-app
directives in <div> tag.
(ii) The second is dependencies module can be pass but it is optional.

Note: After creates the module save at the .html file (same) location with the module_name and .js
extension.

Syntax:

var module_variable = angular.module("module_name", [dependencies module]);

Example:
mymodule.js
var m1 = angular.module("mymodule", []);

(Step 2):Creation of controller

[[ If create the controller into .html file then it creates at the second line of [
var app = angular.module("myApp", []); ]] inside <script></script> tag. ]]

To create the controller module the controller() method is used with


module_vaiableas:m1.controller().

 At the time of creation of controller module must be pass following two parameters.
1. The first is controller_name can be anything.
2. The second is function(). In the function() must be pass@scope parameter as
current_class_object. This @scopeis used to create the variable with dot (.) sign inside the
controller module. The string value must be pass within double quote mark into variable.

[100]
Note: After creates the controller module save at the .html file (same) location with the
controller_name and .js extension.

Syntax:

module_vaiable.controller("controller_name", function($scope)

$scope.variable_name=value;

$scope.variable_name=value;

});

Example:
mycont.js
m1.controller("mycont", function($scope)
{
$scope.name = "Ajeet";
$scope.roll = 545454;
});

(Step 3): Creation of app (application or main html file)

∗ First of all insure that module file (mymodule.js) and controller file (mycont.js) have been
saved at the location of html file (alljs.html).
∗ Using src attribute of <script> tag links the module file (mymodule.js) and controller file
(mycont.js) at before the <body> tag (inside <head> tag) of html file.
∗ Inside <body> or <div> tag specify the module and controller. To specify the module the ng-
app directive and to specify the controller the ng-controllerdirective are used.

Syntax:
<div ng-app="module_name" ng-controller="controller_name">
Expressions or other html statements
</div>

alljs.html
<!DOCTYPE html>
<html>
<head><title> app file</title>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="mymodule.js"></script>
<script src="mycont.js"></script>
</head>
<body>
<div ng-app="mymodule" ng-controller="mycont">
{{name + " " + roll}}

[101]
<!--<h1 ng-bind="name"></h1>
<h1 ng-bind="roll"></h1>-->

<!--<input type="text" ng-model="name"/>


<input type="text" ng-model="roll"/>-->
</div>

</body>
</html>

Output
Ajeet 545454

Creation of module in single HTML file


To create the module into single HTML file there are following steps must be follow.

Step 1: At before the closing of body tag, write the module code inside <script></script> tag. At just
below of module code write the controller code inside same <script></script> tag.

Step 2:
∗ Inside <body> or <div> tag specify the module and controller. To specify the module the ng-
app directive and to specify the controller the ng-controllerdirective are used.

Syntax:
<div ng-app="module_name" ng-controller="controller_name">
Expressions or other html statements
</div>

Example
All.html
<!DOCTYPE html>
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div ng-app="mymodule" ng-controller="mycont">
{{name + " " + roll}}

<!--<h1 ng-bind="name"></h1><h1 ng-bind="roll"></h1>-->

<!--<input type="text" ng-model="name"/>


<input type="text" ng-model="roll"/>-->
</div>

[102]
<script>
var m1 = angular.module("mymodule", []);
m1.controller("mycont", function($scope) {
$scope.name = "Ajeet";
$scope.roll = 545454;
});
</script>
</body>
</html>
Output

Ajeet 545454

Date: 03/DECEMBER/2023, Page 102


------------------------Completed-----------

[103]

You might also like