M2 R5 Web Designing PDF
M2 R5 Web Designing PDF
M2-R5:
Web Designing & Publishing.
[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.
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.
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>
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.
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:
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.
(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:
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:
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:
[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.
boolean represents boolean value either false or true. Class true or false
type is boolean.
(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.
Non- Description
primitive
data Type
Array It provides the fixed-size data structure that stores the elements of the same type.
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;
To print the value the variable must be write inside document.write() method. More than one variables
will be separate by comma (,) sign.
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:
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:
In the javascript storage classes are the another type of variable and used to store the value. There are
two types of storage classes.
[12]
Variables defined with let cannot be redeclared.
Example:
let x = "John Doe";
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
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.
<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.
Syntax: document.getElementById("id1").innerHTML
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:
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:
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:
[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:
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" />
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:
[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.
The prompt() function provides the entered value in string format. To perform the arithmetic operation
must be convert that value in number format.
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:
[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:
(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.
(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.
Note: The ++ and -- are unary operator because it performs the operation on the one values.
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
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:
(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.
(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.
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>---------------------------");
[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.
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:
[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:
Operator Description
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.
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);
[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;
[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;
}
[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:
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.
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:
[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:
<!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;
}
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;
}
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>
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);
</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.
[45]
Syntax:var arrayName = new Array([size]);
Example:
OR
var arr1;
arr1=new Array(5);
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.
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];
[47]
Array declaration and definition (initialization) together
At the time of creation of array we can store the value into array.
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);
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.
On the basis of requirement there are four ways to create the function.
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>
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:
[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.
This function takes any argument and does not return the value. Into the javascript the function has
two parts.
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>
Example:
[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:
This function does not take any argument and return the value from function. Into the javascript the
function has two parts.
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>
Example:
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:
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.
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:          
<input type="text" id="t1"/><br><br>
Enter second number:      
<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]
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:          
<input type="text" id="t1"/><br><br>
Enter second number:      
<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:
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));
[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.
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
There are following mouse related events and their event handlers are:
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'>
[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.
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
[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:
[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:
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:
There are following keyboard related events and their event handlers are:
[67]
Keyup onkeyup When the user release the key.
(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:
There are following form related events and their event handlers are:
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:
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.
[70]
Output:
<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
<!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
There are following web page (window) related events and their event handlers are:
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.
[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:
(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.
[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: Enter name and password and check valid or not? (GOOD)
<html><head><title>web page</title></head>
<body>
<form name="frm1">
Enter your name:      <input type="text" id="t1"/><br>
Enter your password:<input type="text" id="t2"/><br><br>
Press for login :  <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:      <input type="text" id="t1"/><br>
Enter your password:<input type="text" id="t2"/><br><br>
Press for login :  <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 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.
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.
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>
Step 1:First of all write the following URL into address bar of browser.
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:
Step 2: Then click on DOWNLOAD ANGULARJS button. Then open another window as follows.
[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.
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.
(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
The ng-app directive in AngularJS is used to define the root element of an 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.
Syntax:
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
Step 4: Bind the value of above model defined using ng-bind directive
<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:
[85]
<p>{{'Second number: '+7}}</p>
<p>{{'Addition is : '+(5+7)}}</p>
</div>
</body>
</html>
Output:
Syntax:
Contents...
</html_element>
</div>
</body>
[86]
</html>
Output:
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}}
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:
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.
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:
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:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="">
</div>
</body>
</html>
Output
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:
{{ 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>
<ol>
<li ng-repeat = "country in countries">
{{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
</li>
</ol>
</div>
[92]
2. Country: United Kingdom, Locale: en-GB
3. Country: France, Locale: en-FR
It performs the action when click on the object. It can be writes into output html tag like <li>, <p>,
<h1> etc.
<!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.
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 3:testAngularJS.htm
<html>
<head>
<title>AngularJS Expressions</title>
</head>
<body>
<h1>Sample Application</h1>
</body>
</html>
Output
Sample Application
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="">
</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>
[98]
</body>
</html>
Output
Example 2:
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
</body>
</html>
Output
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.
(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.
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().
Note: After creates the module save at the .html file (same) location with the module_name and .js
extension.
Syntax:
Example:
mymodule.js
var m1 = angular.module("mymodule", []);
[[ If create the controller into .html file then it creates at the second line of [
var app = angular.module("myApp", []); ]] inside <script></script> tag. ]]
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;
});
∗ 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>-->
</body>
</html>
Output
Ajeet 545454
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}}
[102]
<script>
var m1 = angular.module("mymodule", []);
m1.controller("mycont", function($scope) {
$scope.name = "Ajeet";
$scope.roll = 545454;
});
</script>
</body>
</html>
Output
Ajeet 545454
[103]