0% found this document useful (0 votes)
2 views155 pages

Unit I Client Side Scripting

This document covers the fundamentals of client-side scripting with JavaScript, including its definition, advantages, limitations, and best practices. It explains how JavaScript enhances user experience through dynamic web pages and outlines the differences between client-side and server-side scripting. Additionally, it provides guidelines on variable declaration, data types, and coding conventions for effective JavaScript programming.
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)
2 views155 pages

Unit I Client Side Scripting

This document covers the fundamentals of client-side scripting with JavaScript, including its definition, advantages, limitations, and best practices. It explains how JavaScript enhances user experience through dynamic web pages and outlines the differences between client-side and server-side scripting. Additionally, it provides guidelines on variable declaration, data types, and coding conventions for effective JavaScript programming.
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

Unit 1

Client-Side Scripting
Introduction
Learning Objectives
After this unit students will be able to:
▪ Understand basics of client-side scripting with JavaScript

▪ Develop and debug JavaScript programs

▪ Manipulate DOM effectively using modern methods

▪ Handle browser events with addEventListener

▪ Implement client-side form validation with regex

▪ Use cookies, localStorage and best practices


What is Scripting ?
• A scripting language is a type of programming language that is used to
write scripts.

• Scripts are typically short programs that automate tasks or control the
behavior of software applications.

• Scripting languages are usually interpreted, meaning they are executed


line by line by an interpreter at runtime rather than being compiled into
machine code beforehand.

• Some Scripting languages are JavaScript, Python, PHP, Ruby.


Client-Side Scripting

• Client-side scripting refers to code that is executed on


the user's browser rather than on the web server.
• It enables interactive web pages by allowing scripts to
respond to user actions.
• JavaScript is the primary client-side scripting language.
✓ JavaScript was originally developed as a scripting language,
but today it is considered a full programming language
used for both client-side and server-side development.
Client-Side Scripting (Contd.)

It encompasses the user interface (UI) components responsible for


displaying content and interacting with users, as well as client-side
scripting languages like JavaScript for dynamic behavior.
JavaScript
▪ JavaScript is a versatile scripting language commonly used for creating
dynamic and interactive web pages.
▪ Developed initially for web browsers, it has evolved into a powerful and
widely-used programming language.
▪ JavaScript was created by Brendan Eich while he was working at Netscape
Communications Corporation.
▪ Originally developed in just 10 days.
▪ The language was initially named Mocha, later renamed to LiveScript, and
finally to JavaScript.
▪ JavaScript is one of the core technologies of the web, alongside HTML and
CSS.
JavaScript (Contd.)
▪ Supported by all modern web browsers.
▪ Widely used for both client-side and server-side development ([Link]).
▪ JavaScript plays a crucial role in modern web development by enabling
the creation of dynamic content and interactive user interfaces.
▪ It allows developers to enhance the user experience by adding
functionalities like form validation, animations, and real-time updates
without the need to reload the entire page.
▪ As a client-side scripting language, JavaScript executes in the user's
browser, reducing the server load and contributing to a more responsive
and engaging web environment.
JavaScript: Scripting Language or Programming Language?
▪ Originally created as a scripting language for web browsers.
▪ Today, JavaScript is considered a full programming language because it
supports:
▪ Object-oriented programming
▪ Functional programming
▪ Event-driven programming
▪ Client-side and server-side development ([Link])
▪ Supports OOP, Functional, and Event-driven paradigms.
▪ Modern JavaScript (ES6+) features: let/const, arrow functions, template
literals, modules
▪ Therefore, JavaScript started as a scripting language but has evolved into a
complete programming language.
Advantages of JavaScript
▪ Client-Side Execution
▪ Speed and Performance
▪ Versatility and Flexibility
▪ Rich Interfaces
▪ Wide Adoption and Community Support
▪ Asynchronous Programming
▪ Cross-Platform Development
▪ Ease of Learning and Use
▪ Browser Compatibility
▪ Integration with APIs
▪ Continuous Evolution
Limitations of JavaScript
▪ Security concerns

▪ Browser inconsistencies

▪ Performance issues

▪ Client dependency

▪ Complexity in large applications

▪ Cannot directly access local files

▪ Browser security sandbox


Need of Client-Side Scripting Language
Why Use Client-Side Scripting?
▪ Enhances User Experience

▪ Creates dynamic and interactive web pages.

▪ Reduces Server Load

▪ Processes user interactions on the client side, reducing server

requests.

▪ Faster Responses

▪ Provides immediate feedback to user actions without needing a server

round trip.
Why Use Client-Side Scripting?
Why Use Client-Side Scripting?
Client-Side Scripting vs Server-Side Scripting

Client-Side Scripting Server-Side Scripting

▪ Runs in the user's browser. ▪ Runs on the web server.

▪ Provides immediate feedback ▪ Processes data and handles


to user actions. database interactions.
Disadvantages of Client-Side Scripting

▪ Security Concerns:

▪ Scripts can be viewed and manipulated by users, potentially leading to

security vulnerabilities.

▪ Browser Compatibility:

▪ Different browsers may interpret scripts differently, causing inconsistencies.

▪ Performance:

▪ Heavy or poorly optimized scripts can slow down the browser, affecting

user experience.
Formatting and Coding Convention
Code Formatting

▪ Whitespace: Use spaces around operators and after commas for readability.

▪ Line Breaks: Use line breaks after blocks of code, before and after function definitions.

▪ Object and Array Literals: Consistently use spacing and line breaks for readability.
e.g., { key: value }).
Naming Conventions
▪ Variables: Use camelCase //Variable
let firstName = "Alice";
(e.g., firstName, totalAmount).
//Function
function getData() {
// Retrieve data
}
▪ Functions: Use camelCase and start with a verb
//Constant
(e.g., calculateTotal, fetchData). const MAX_COUNT = 50;

//Class
class User {
constructor(name) {
▪ Constants: Use UPPER_CASE with underscores [Link] = name;
}
(e.g., MAX_SIZE, PI). }

▪ Classes: Use PascalCase


(e.g., UserProfile, OrderManager).
Modern JavaScript Best Practices (ES6+)
▪ Always start with "use strict";Prefer const → let → avoid var

▪ Use arrow functions () => {} for callbacks

▪ Use template literals `Hello ${name}` instead of +Meaningful variable & function names

(camelCase)

▪ Always declare variables before use

▪ Write JSDoc comments for functions

▪ Follow consistent indentation (2 or 4 spaces)

▪ Use addEventListener() instead of inline events

▪ Prefer textContent over innerHTML for security


Code Structure
//Indentation with two spaces

function checkAge(age) {
▪ Indentation: Use 2 or 4 spaces for if (age < 18) {
alert("You are a minor.");
} else {
indentation (no tabs). alert("You are an adult.");
}
}
▪ Braces: Use curly braces {} for blocks of
//Function Block
code (e.g., functions, loops).
function interestRate(principal, rate, time) {
return (principal * rate * time) / 100;
▪ Statements: End each statement with a }

semicolon (;).

▪ Line Length: Keep lines under 80 characters

for better readability.


Comments
Comments /**
* Calculates the area of a rectangle.
* @param {number} width - The width of the rectangle.
1. Single-line Comment * @param {number} height - The height of the rectangle.
* @returns {number} The total calculated area.
*/
▪ Use // for short explanations.
function calculateRectangleArea(width, height) {
2. Multi-line Comments // Return early if dimensions are invalid
if (width <= 0 || height <= 0) return 0;
▪ Use /* ... */ for detailed descriptions.
return width * height;
}
3. JSDoc

▪ professional documentation style

▪ Use JSDoc comments (/** ... */) for documenting

functions, parameters, and return values.


Best Practices

▪ Keep comments clear, concise, and relevant.

▪ Avoid obvious comments.


//Initialize a counter
let counter = 0;

/*
Increment counter by 1
*/

Comments in function incrementCounter() {


counter++;
JavaScript }

/**
* Calculate area of a rectangle
* @param {number} width - Rectangle width
* @param {number} height - Rectangle height
* @returns {number} The area of the rectangle
*/

function calculateArea(width, height) {


return width * height;
}

//Whitespace around operators and after commas


let sum = a + b;
let array = [1, 2, 3];

//Line breaks after blocks and functions


function add(a, b) {
return a + b;
}

//Object literal with consistent formatting


const person = {
name : "Dibya",
age : 5
};
Using Script Tag
Embedding JavaScript in HTML
JavaScript Files
Noscript Tag
The Script Tag
The <script> tag is used to embed or reference JavaScript in an HTML document.
<script>
alert("Hello");
</script>

Place scripts before the closing </body> tag for faster page loading.
<body>

<h1>Hello</h1>

<script src="[Link]"></script>

</body>
Embedding JavaScript in HTML : Inline JavaScript

Place JavaScript code within HTML tags using the onclick, onchange, etc., attributes.

<button onclick="alert('Hello, Students!')">Click Me</button>


Embedding JavaScript in HTML : Internal JavaScript
Include JavaScript code within the <script> tag in the HTML document.

<!DOCTYPE html>
<html lang="en">

<head>
<title>
Internal JS
</title>
</head>

<body>
<button id="myButton">Click Me</button>
<script>
[Link]('myButton').onclick = function () {
alert('Hello');
};
</script>
</body>

</html>
Embedding JavaScript in HTML : External JavaScript
Link to an external JavaScript file using the <script> tag with the src attribute. For larger
projects, it's common to place your JavaScript code in a separate external file (e.g.,
[Link]) and link it to your HTML file.

//[Link] //[Link]

<!DOCTYPE html> [Link]("myButton").onclick =


<html lang="en"> function () {
alert("Hello");
<head> };
<title> Internal JS </title>
<script src="[Link]" defer></script>
</head>

<body>
<button id="myButton">Click Me</button>
</body>

</html>
Script Loading Attributes
<script src="[Link]" defer></script>
<script src="[Link]" async></script>

defer async
Downloads while HTML is parsed. Downloads while HTML is parsed.
Executes after HTML parsing is complete. Executes immediately after download.
Preserves script order. Does not guarantee script order.
Ideal for main website scripts. Ideal for analytics, ads, and tracking scripts.

Modern Practice
▪ Use defer for most JavaScript files.
▪ Use async for independent third-party scripts.
▪ Improves page loading performance by preventing render-blocking.
Inline vs Internal vs External

Feature Inline JavaScript Internal JavaScript External JavaScript


Inside HTML element Inside <script> tags in an HTML
Location In a separate .js file.
attributes page.

Use Case Small, simple interactions. Page-specific functionality. Large and reusable application logic.

Code
Mixed with HTML. Partially separated from HTML. Completely separated from HTML.
Organization

Caching Not cached separately. Not cached separately. Cached by the browser.

Maintenance Hard to maintain and debug. Manageable for small projects. Easy to maintain and scale.
Quick testing or simple Professional and large-scale
Best For Small to medium web pages.
actions. websites.
JavaScript Files
A JavaScript file is a separate file with a .js extension that contains JavaScript code.

Advantages:
• Code Reusability
• Easy Maintenance
• Better Organization
• Faster Loading through Browser Cache
Linking JavaScript Files <!-- [Link] -->
<!DOCTYPE html>
<html>
1. Create HTML File <head>
<title>External JS Demo</title>
▪ Create a new file and save it as </head>
<body>
[Link]. <button onclick="greet()">Say Hello</button>
▪ Add basic HTML structure and a
<!-- Link external JavaScript file -->
button that will call the greet() <script src="[Link]"></script>
</body>
function. </html>

2. Create the JavaScript file


// [Link]
▪ In the same folder, create another function greet() {
file and save it as [Link]. alert("Hello");
}
▪ Write the greet() function inside
this file.

Note:
Make sure both files, [Link] and [Link] in the same folder so <script src="[Link]"></script> can
find the file correctly.
<noscript>
▪ The <noscript> element is used to offer content or messages to users who
have JavaScript disabled or when JavaScript is not supported by the browser.

<noscript>
<!-- Content for users with JavaScript disabled -->
Syntax:
</noscript>

<body>
<h1>Welcome to My Website</h1>

<noscript>
<p style="color:red;"> JavaScript is disabled in your browser.</p>
</noscript>
Example:
<script>
[Link]("<p>JavaScript is enabled!</p>");
</script>

</body>
</html>
Variables and Data Types
Variables: Definition, Declaration, and Assignment

Definition: In JavaScript, variables are containers for storing


data values. They are declared using the var, let, or const
keyword.

Declaration: To declare a variable, you use one of the


keywords (var, let, or const) followed by the variable name.
For example: var myVariable;

Assignment: Variables can be assigned values using the


assignment operator =. For example: myVariable = 10; or
combined declaration and assignment: var myVariable = 10;
When to Use var, let, or const?

1. Always declare variables.

2. Always use const if the value should not be changed.

3. Always use const if the type should not be changed (Arrays and Objects).

4. Only use let if you can't use const.

5. Only use var if you MUST support old browsers.


Data Types

1. Primitive data types:

▪ null

▪ undefined

▪ boolean

▪ number

▪ string

▪ symbol – available from ES2015

▪ bigint – available from ES2020

2. Complex / Reference data type

▪ Object
Data Types : Overview
Type Category Example

Number Primitive 42 / 3.14 / NaN

String Primitive "hello" / 'world'

Boolean Primitive true / false

Null Primitive null

Undefined Primitive undefined

Symbol Primitive Symbol('id')

BigInt Primitive 9007199254740991n

Object Reference { } / [ ] / function


Data Types: Number
▪ Represents numeric values.
▪ Supports integers and decimals.
▪ Includes Infinity and NaN.

✓Syntax: let age = 25;


let price = 99.99;

let variableName = value; [Link](age); // 25


[Link](price); // 99.99
[Link](typeof age); // number
✓ Example:

let age = 25;


Data Types: String
▪ Immutable sequence of UTF-16 characters - methods return new strings

▪ Three quote styles: ' " `

▪ Template literals support expressions

▪ Strings are zero-indexed


let name = "John";
✓ Syntax [Link](name); // John
[Link]([Link]); // 4
let variableName = "text"; [Link]([Link]()); // JOHN

✓ Example
let name = "John";
Data Types: Boolean
▪ Stores true or false values.

▪ Used in conditional statements.

▪ Represents logical data.

✓ Syntax let isLoggedIn = true;

let variableName = true | false; [Link](isLoggedIn); // true


[Link](Boolean(0)); // false
[Link](Boolean("JS")); // true
✓ Example

let isLoggedIn = true;


Data Types: Null

▪ Represents intentional absence of value.

▪ Assigned by the programmer.

▪ Used for empty objects or data.

✓ Syntax
let user = null;
let variableName = null;
[Link](user); // null
✓ Example [Link](user === null); // true
[Link](typeof user); // object
let user = null;
Data Types: Undefined

▪ Variable declared but not assigned.

▪ Automatically assigned by JavaScript.

▪ Represents missing value.

✓ Syntax
let score;
let variableName;
[Link](score); // undefined
✓ Example [Link](typeof score); // undefined
[Link](score === undefined);// true
let score;
Data Types: Symbol

▪ Creates unique identifiers. const id1 = Symbol("id");


const id2 = Symbol("id");
▪ Introduced in ES6.
[Link](id1 === id2); // false
[Link](typeof id1); // symbol
▪ Often used as object keys.

✓ Syntax
let variableName = Symbol("description");

✓ Example

const id = Symbol("userId");
Data Types: Bigint

▪ Stores very large integers.

▪ Introduced in ES2020.

▪ Uses 'n' suffix.

const population = 8000000000n;

✓ Syntax [Link](population); // 8000000000n


[Link](population + 1n); // 8000000001n
let variableName = 123n; [Link](typeof population); // bigint

✓ Example

const population = 8000000000n;


Data Types: Object

▪ Stores data as key-value pairs.

▪ Reference data type.

▪ Can contain properties and methods.

✓ Syntax
const objectName = { const student = {
name: "Alice",
property: value
age: 20
}; };

✓ Example [Link]([Link]); // Alice


[Link]([Link]); // 20
const student = { [Link](typeof student); // object
name: "Alice",
age: 20
};
typeof Operator
▪ The typeof operator is used to identify the data type of a value or variable and
returns the type as a string.

Syntax: typeof value or typeof(variable)

typeof 5; // "number"
typeof "Hello"; // "string"
Example: typeof true; // "boolean"
typeof null; // "object"

Key Points
▪ Determines the data type of values and variables.
▪ Returns the type as a string.
▪ Useful for debugging and type checking.
▪ Common outputs: "number", "string", "boolean", "object", "undefined".

Exam Tip: typeof null returns "object".


Operators
Types of Operators
▪ Arithmetic Operators
+, -, *, /, %, ** (exponent)
▪ Assignment Operators
=, +=, -=, *=, /=, %=, **=
▪ Comparison Operators
== (equal), === (strict equal), !=, !==, >, <, >=, <=
▪ Logical Operators
&& (AND), || (OR), ! (NOT)
▪ String Operators
+ (concatenation)
▪ Ternary (Conditional) Operator
condition ? valueIfTrue : valueIfFalse
Types of Operators (Contd.)

▪ Other Operators
▪ Type:
typeof, instanceof
▪ Bitwise
&, , ^, ~, <<, >>
▪ Comma
,
let x = 10, y = 20;

Example let result = (x + y > 25) ? "Greater" : "Smaller";

[Link](result); // Greater
Control Structures
Control Structures
▪ Control structures are programming constructs that dictate the flow of
execution in a program based on certain conditions or iterations.
▪ They allow a program to make decisions and repeat actions, enabling
dynamic and flexible behavior.
▪ Control Structures in JavaScript
▪ Conditional Statements: Execute different blocks of code based on conditions
(e.g., if, else if, else, switch).
▪ Loops: Repeat a block of code multiple times (e.g., for; while; do...while).
▪ Switch Statement: A type of conditional statement that selects one of many
blocks of code to execute based on the value of an expression.
Control Structures – Conditional Statements

▪ Control structures allow the program to make decisions and repeat tasks.

1. if Statement

if (condition) {
// Code executes if condition is true
Syntax
}

let age = 20;


if (age >= 18) {
Example [Link]("You are eligible to vote.");
}
Control Structures – Conditional Statements (Contd.)

2. if … else Statement

if (condition) {
// True block
Syntax } else {
// False block
}

let marks = 75;


if (marks >= 40) {
[Link]("Pass");
Example } else {
[Link]("Fail");
}
Control Structures – Conditional Statements (Contd.)
3. if...else if...else & Nested if
if (condition1) {
// Block 1
} else if (condition2) {
Syntax // Block 2
} else {
// Default block
}
let score = 85;
if (score >= 90) {
[Link]("Grade: A");
} else if (score >= 75) {
Example [Link]("Grade: B");
} else if (score >= 60) {
[Link]("Grade: C");
} else {
[Link]("Grade: F");
}
Control Structures – Loops
▪ Loops are used to execute a block of code repeatedly based on a
condition.

▪ For Loop: Repeats a block of code a specific number of times.

▪ While Loop: Repeats a block of code while a condition is true.

▪ Do...While Loop: Repeats a block of code at least once, then continues


while a condition is true.
Control Structures – Loops (Contd.)
for (let i=0; i<5; i++) {
For Loop [Link](i); // This will log numbers 0 to 4
}

let j=0;
while (j<5) {
While Loop
[Link](j); // This will log numbers 0 to 4
j++;
}

let k=0;
do {
[Link](k); // This will log numbers 0 to 4
Do While Loop k++;
} while (k<5);
Control Structures – Jump Statements – break, continue, labeled

▪ Jump Statements
▪ break – Exits the loop/switch completely.
▪ continue – Skips the current iteration and moves to next.
▪ Labeled Statements – Used with nested loops for precise control.

// break Labeled Break (for nested loops)


for (let i = 1; i <= 10; i++) {
if (i === 6) break;
[Link](i); // Prints 1 to 5 outerLoop: for (let i = 1; i <= 3; i++) {
} innerLoop: for (let j = 1; j <= 3; j++) {
if (i === 2 && j === 2) {
// continue break outerLoop;
for (let i = 1; i <= 5; i++) { }
if (i === 3) continue; [Link](`i=${i}, j=${j}`);
[Link](i); // Prints 1,2,4,5 }
} }
Switch Case

▪ The switch statement is used to perform different actions based on different conditions.
▪ It’s a cleaner alternative to multiple if-else statements when dealing with numerous
possible values.

switch (expression) { let day=2;


case value1: switch(day){
// Statement(s) or Block of code case 1:
break; [Link]("Sunday");
case value2: break;
// Statement(s) or Block of code case 2:
break; [Link]("Monday");
case value3: break;
// Statement(s) or Block of code case 3:
break; [Link]("Tuesday");
default: break;
// Default statement(s) or Default block of code default:
} [Link]("Invalid day");
}
Array and ForEach Loop
Arrays
Arrays are a fundamental data structure in JavaScript, allowing you to store
multiple values in a single variable. They are versatile and can hold any data
type, including numbers, strings, objects, and even other arrays. Let's explore the
basics of arrays in JavaScript.

Creating Arrays
Arrays can be created using the array literal syntax or the Array constructor.
▪ Array Literal Syntax:
let fruits = ["Apple", "Banana", "Cherry"];
▪ Array Constructor:
let fruits = new Array("Apple", "Banana", "Cherry");
Array Types
1) Single-Dimensional Arrays
The most common type of array, which holds a list of elements in a single
dimension.
let numbers = [1, 2, 3, 4, 5];

2) Multi-Dimensional Arrays
Arrays that contain other arrays as elements, allowing for a matrix-like structure.

let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
Array Types
3) Objects as Key-Value Collections

JavaScript doesn't support associative arrays like some other


languages, but objects can be used to store key- value pairs.

let person = {
firstName: "John",
lastName: "Doe",
age: 30,
city: "New York"
}
Accessing Array Data

▪ Array elements are accessed using zero-based indexing.


▪ The first element has an index of 0, the second has an index of 1, and so on.

let fruits = ["Apple", "Banana", "Cherry"];


[Link](fruits[0]); // Output: Apple
[Link](fruits[1]); // Output: Banana
[Link](fruits[2]); // Output: Cherry

let fruits = ["Apple", "Banana", "Cherry"];


fruits[1] = "Blueberry";
[Link](fruits); // Output: ["Apple", "Blueberry", "Cherry"]
Array Properties and Methods

Length Property: Returns the number of elements in the array.

let fruits = ["Apple", "Banana", "Cherry"];


[Link]([Link]); // Output: 3

push(): Adds one or more elements to the end of an array and returns the
new length of the array.

[Link]("Suntala");
[Link](fruits); // Output: ["Apple", "Banana", "Cherry", "Suntala"]
Array Properties and Methods
pop(): Removes the last element from an array and returns that
element.
let lastFruit = [Link]();
[Link](lastFruit); // Output: "Suntala"
[Link](fruits); // Output: ["Apple", "Banana",
"Cherry", "Suntala", ]

shift(): Removes the first element from an array and returns that
element.
let lastFruit = [Link]();

[Link](firstFruit); // Output: "Apple"


[Link](fruits); // Output: ["Banana", "Cherry", "Suntala", ]
Array Properties and Methods

unshift(): Adds one or more elements to the beginning of an array and


returns the new length of the array.
let lastFruit = [Link]();

[Link](fruits); // Output: ["Apricot",


"Banana", "Suntala", ]

indexOf(): Returns the first index at which a given element can be found
in the array, or -1 if it is not present.

let index = [Link]("Banana");

[Link](index); // Output: 1
Iterating Over Arrays : For Loop

// Iterating Over an Array

const fruits = ['apple', 'banana', 'cherry'];


for (let i = 0; i < [Link]; i++) {
[Link](fruits[i]);
}
Iterating Over Arrays : For Each Loop
// Iterating Over Arrays : For Each Loop

let fruits = ['Apple', 'Banana', 'Mango', 'Orange’];

[Link](function(fruit) {
[Link](fruit);
});

//Output:
// Apple
// Banana
// Mango
// Orange
Modern Array Methods (ES6+)

▪ forEach() – Iterate
▪ map() – Transform array
▪ filter() – Select items
▪ find() – Find first match
▪ reduce() – Accumulate value
▪ includes() – Check existence

const numbers = [1, 2, 3, 4, 5];

const doubled = [Link](n => n * 2);


const evens = [Link](n => n % 2 === 0);
const sum = [Link]((acc, n) => acc + n, 0);
Functions
Functions in JS
▪ A function is a block of code that performs an action or
returns a value.
▪ Functions are custom code defined by programmers that
are reusable and can therefore make your programs
more modular and efficient.

function addNumbers(a, b) {
return a + b;
}
How to create function in JS
▪ Use the keyword function followed by the name of the function.
▪ After the function name, open and close parenthesis.
▪ After parenthesis, open and close curly braces.
▪ Within the curly branches, write your lines of code
//defining a function
function <function-name>(parameters) {
//function body
}

<script>
function welcome() {
alert("Functions in JavaScript!");
}
Welcome();
</script>
Function Parameters
▪ Function parameters are additional information passed to a
function.
▪ A function in JavaScript can have any number of parameters and
at the same time a function in JavaScript can not have a single
parameter.

Function Invocation / Calling Functions


The code inside the function will execute when "something"
invokes (calls) the function:
▪ When an event occurs (when a user clicks a button)
▪ When it is invoked (called) from JavaScript code
▪ Automatically (self invoked)
//Function with parameter

function greet(name) {
Function [Link]("Hello, " + name + "!");
with }
parameter
greet("Alice"); // Output: Hello, Alice!

//Function with parameter

function add(a, b) {
Function return a + b;
}
with return var sum = add(5, 3);
value [Link](sum); // Output: 8
//Function with default parameters
function greet(name = "Guest") {
Function [Link]("Hello, " + name + "!");
}
with default greet(); // Output: Hello, Guest!
parameters greet("Bob"); // Output: Hello, Bob!

//Function with rest parameters


function sumAll(...numbers) {
return [Link]((total, num) => total
Function + num, 0);
with rest }
parameters
var total = sumAll(1, 2, 3, 4);
[Link](total); // Output: 10
The arguments Object in JavaScript Functions

//Argument object in Functions in JavaScript

function myFunction() {
[Link](arguments);
[Link]([Link]);
[Link](arguments[0]);
[Link](arguments[1]);
}

//Output:
//Arguments(3) ['Hello', 'World', '!', callee: ƒ,
Symbol([Link]): ƒ]
//3
//Hello
//World
Nested Functions in JavaScript

//Nested functions

function outerFunction() {
var outerVariable = 'I am from the outer function';

function innerFunction() {
var innerVariable = 'I am from the inner function';
[Link](outerVariable);
[Link](innerVariable);
}

innerFunction();
}
outerFunction();

//Output:
//I am from the outer function
//I am from the inner function
Arrow Functions in JavaScript

//Arrow Function
//ES5
function add(a, b) {
return a + b;
}

//ES6
const add = (a, b) => a + b; //Output: 5

//ES5
var numbers = [1, 2, 3];
var squares = [Link](function (num) {
return num * num;
});

//ES6
const numbers = [1, 2, 3];
const squares = [Link](num => num * num); //Output: [1, 4, 9]
Callback Functions in JavaScript

A callback function in JavaScript is a


function myFunction(name, callback) {
function that is passed as an argument [Link]("Hello " + name);
to another function and is executed callback();
after a specific task is completed. In this }
example, myFunction accepts a name
function myDisplayer() {
and a callback function. It first prints [Link]("I am a callback
"Hello John" and then calls the callback function");
using callback(). Since myDisplayer is }

passed as the callback, it runs next and myFunction("John", myDisplayer);


prints "I am a callback function".
Callbacks are commonly used to
//Output
execute code in a specific order and to Hello John
handle asynchronous operations such I am a callback function
as events, timers, and API requests.
Built-in Objects
Common Built-in Methods
charAt(index) : returns the character at the specified index.

Example:
const str = "Hello";
[Link]([Link](1)); // "e"

includes(substring) : checks if a substring exists within the string.

Example:
const str = "Hello World";
[Link]([Link]("World")); // true
Common Built-in Methods
substring(start, end): extracts a part of the string between start and
end.

Example:
const str = "Hello World";
[Link]([Link](0, 5)); // "Hello"

split(separator): splits the string into an array of substrings based on


the separator.

Example:
const str = "Hello World";
[Link]([Link](" ")); // ["Hello", "World"]
Common Built-in Methods
trim(): removes whitespace from both ends of the string.

Example:
const str = " Hello World! ";
[Link]([Link]()); // "Hello World!"

isNaN(value): determines whether a value is NaN (Not-a- Number).

Example:
const value = NaN;
[Link](isNaN(value)); // true
Date Objects
Date Functions
1) Current Date and Time

const now = new Date();


[Link](now); // Prints the current date and time

2)Specific Date and Time

const specificDate = new Date('2024-08-10T10:00:00');


[Link](specificDate); // Prints the specified date and time
Date Functions
3) Get Current Year

const now = new Date();


[Link]([Link]()); // Gets the full year (e.g., 2024)

4)Get Current Month, Day

const now = new Date();


[Link]([Link]()); // Gets the month (0-indexed, e.g., 7
for August)
[Link]([Link]()); // Gets the day of the month (e.g., 10)
Date Functions
5) Calculate Difference Between Dates

const date1 = new Date('2024-08-10');


const date2 = new Date('2024-09-10');
const differenceInTime = [Link]() - [Link]();
const differenceInDays = differenceInTime / (1000 * 3600 * 24); //

Convert milliseconds to days


[Link](differenceInDays); // Difference in days
Working with Date Object

▪ Create current date: new Date()


▪ Specific date: new Date('2026-06-15’)
▪ Get values:
▪ getFullYear(), getMonth(), getDate()
▪ getHours(), getMinutes()

const today = new Date();


const future = new Date(‘2026-12-31’);
const diffDays = [Link]((future - today) / (1000*3600*24));
Working with Timing Functions
Timing Functions: Control the execution of code at specified intervals.
//Execute code after 2 seconds

setTimeout(function() {
[Link]("Hello, World!");
Methods }, 2000);
▪ setTimeout()
//Repeat code every 3 seconds
▪ setInterval()
setInterval(function() {
▪ clearTimeout() [Link]("This message will repeat every 3 seconds.");
}, 3000);
▪ clearInterval()

//Stop the interval after 10 seconds

setTimeout(function() {
clearInterval(myInterval);
}, 10000);
Interacting with Browser
Interacting With the Browser
▪ Interacting with the Browser refers to the ability of JavaScript to
communicate with and control various features of a web browser such
as displaying messages, collecting user input, navigating browser
history, opening windows, and executing timed operations.
▪ JavaScript achieves this through the Browser Object Model (BOM).
▪ Common Browser Interactions

▪ Display messages

▪ Receive user input

▪ Navigate browser history

▪ Open and manage browser windows

▪ Execute timed operations


Examples

▪ Window Object ▪ [Link](-1);

▪ [Link](message);

▪ [Link](message); ▪ Location

▪ [Link](message); ▪ [Link];

▪ [Link](); ▪ [Link];

▪ [Link](); ▪ [Link];

▪ [Link]();

▪ History Object
▪ [Link]();

▪ [Link]();
Windows and Frames
Window Objects
▪ The Window Object represents the browser window in which your web
page is running.
▪ It is the global object in JavaScript, meaning all global variables,
functions, and objects belong to it.
▪ Every browser tab or window has its own window object.
▪ Provides methods for:
▪ Opening/closing windows
▪ Navigating and scrolling
▪ Resizing and moving windows
▪ Showing alerts, prompts, and confirmations
▪ Timers (setTimeout, setInterval)
▪ Interacting with cookies and storage
Window Objects (Contd.)

Method Syntax Description

[Link]() [Link](url, name, features) Opens a new browser window/tab

[Link]() [Link]() Closes the current window

[Link]() [Link](x, y) Scrolls to position (x, y)

[Link]() [Link](width, height) Resizes window to given width and height


Window Objects : Example 1 – [Link]()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>[Link]() Example</title>
</head>
<body>

<h2>[Link]() — Open a New Window</h2>


<p>Click the button to open a new browser window.</p>

<button onclick="openNewWindow()">Open New Window</button>

<script>
function openNewWindow() {
[Link](
"[Link]
"NewWindow",
"width=400,height=300,resizable=yes,scrollbars=yes"
);
}
</script>

</body>
</html>
Window Objects : Example 2 – scrollTo()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>[Link]() Example</title>
</head>
<body>

<h2>[Link]() — Scroll to a Position</h2>


<p>Click the buttons to scroll the page.</p>

<button onclick="scrollTop()">Scroll to Top (0, 0)</button>


<button onclick="scrollTo500()">Scroll to (0, 500)</button>
<button onclick="scrollSmooth()">Scroll Smoothly to (0, 500)</button>

<br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br>

<h3>Target Section</h3>
<p>You have scrolled to this section!</p>
Window Objects : Example 2 (Contd.)

<script>
function scrollTop() {
// Scroll to top
[Link](0, 0);
}
function scrollTo500() {
// Scroll to position (0, 500)
[Link](0, 500);
}

function scrollSmooth() {
// Scroll smoothly to (0, 500)
[Link]({
left: 0,
top: 500,
behavior: "smooth"
});
}
</script>

</body>
</html>
Frames
▪ An iframe (Inline Frame) is an HTML element that allows one webpage to
be displayed inside another webpage. It creates a separate browsing area
with its own document, window, and JavaScript context.
▪ JS Context: JavaScript views an iframe as a separate window with its own
document object model.
▪ Common Use Cases
▪ Media Embedding: Integrating YouTube videos or Google Maps directly.
▪ Isolated Content: Previewing user-uploaded HTML code without breaking main site
styles.
▪ Third-Party Services: Loading secure payment gateways or external chat widgets
safely.

<iframe
<iframe
id="myFrame“
src="[Link]
src=“[Link]
width="600"
width="600”
height="400">
height="400“
</iframe>
title="Sample Framework">
</iframe>
Frame : Concept

▪ An iframe behaves like a mini-browser Main Web Page


inside a webpage. |
| HTML Document
▪ It loads another HTML page. | JavaScript
▪ The iframe has: |
▪ Its own DOM | IFRAME
▪ Its own JavaScript execution |
| Separate HTML Document
environment | Separate DOM
▪ Its own Window object | Separate Window Object

▪ JavaScript can communicate with the


iframe if security rules allow it.
iframe: try it out !!!

<script>
const frame = [Link]('iframe’);
[Link] = 'about:blank';
[Link](frame);

const frameDoc = [Link] || [Link];


[Link]();
[Link]('<h1>Hello from inside the iframe!</h1>’);
[Link]();
</script>
Document Object Model (DOM)
Javascript DOM
The Document Object Model (DOM) is a programming
interface provided by web browsers that allows
JavaScript to interact with and manipulate the structure,
style, and content of a web page. It represents the HTML
document as a tree of nodes, where each node
corresponds to a part of the document, such as
elements, attributes, and text content. The DOM provides
methods and properties to access and modify these
nodes, enabling dynamic web applications.
DOM Tree Structure
The DOM represents a document as a hierarchical tree structure with a
root node (document), branches (elements), and leaves (text nodes).

<!DOCTYPE html>
<html lang="en"> The DOM tree for this document would

<head> have html as the root, with head and


<title>Hello World</title>
</head>
body as child nodes. head would have
title as its child, and body would have
<body>
<h1>Hello World</h1> h1 and p as its children.
<p>This is a simple HTML file. </p>
</body>

</html>
Accessing DOM Elements
▪ JavaScript provides methods to access and
manipulate DOM elements.

▪ Common methods:
❑ getElementById
❑ getElementsByClassName
❑ getElementsByTagName
❑ querySelector
❑ querySelectorAll
Accessing DOM Elements
1) By ID:
▪ Heading: getElementById
▪ Access an element by its id attribute.
▪ Syntax: [Link]('id')

//HTML

<p id="myParagraph">Hello, world!</p>

//JS

var paragraph = [Link]('myParagraph');


[Link]([Link]);
Accessing DOM Elements
2) By Class:
▪ Heading: getElementsByClassName
▪ Access elements by their class attribute.
▪ Returns a live HTMLCollection
▪ Syntax: [Link]('className')

//HTML
<div class="myClass">Item 1</div>
<div class="myClass">Item 2</div>

//JS
var items = [Link]('myClass');
[Link](items[0].textContent);
Accessing DOM Elements
3) By TagName:
▪ Heading: getElementsByTagName
▪ Access elements by their tag name.
▪ Returns a live HTMLCollection.
▪ Syntax:
[Link]('tagName')
//HTML
<p>First paragraph</p>
<p>Second paragraph</p>

//JS
var paragraphs = [Link]('p');
[Link]([Link]); //Output: 2
Accessing DOM Elements
4) By querySelector:
▪ Heading: querySelector
▪ Access the first element that matches a CSSselector.
▪ Syntax: [Link]('selector')

<!-- HTML -->


<p class="myClass">Hello</p>

// JavaScript
var element = [Link]('.myClass');

[Link]([Link]); // Output: Hello


Accessing DOM Elements
5) By querySelectorAll:

▪ Heading: querySelector
▪ Returns a static NodeList.
▪ Syntax:
[Link]('selector')
<!-- HTML -->
<p class="myClass">Item 1</p>
<p class="myClass">Item 2</p>

// JavaScript
var elements = [Link]('.myClass');
[Link]([Link]); // Output: 2
DOM Manipulation : Changing Text Content
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change Text Content</title>
</head>
<body>
<h1 id="header">Old Header</h1>
<button id="changeTextButton" onclick="changeText()">Change Header Text</button>

<script>
function changeText() {
var header = [Link]('header');
[Link] = 'New Header';
}
</script>
</body>
</html>
DOM Manipulation : Modifying Styles
<style>
.box {
width: 100px;
height: 100px;
background-color: red;
}
</style>

<body>
<div class="box" id="box"></div>
<button onclick="changeStyle()">Change Box Style</button>

<script>
function changeStyle() {
var box = [Link]('box');

[Link] = 'blue';
[Link] = '200px';
[Link] = '200px';
}
</script>
</body>
DOM Manipulation : Adding and Removing Classes
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add/Remove Classes</title>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<p id="paragraph">This is a paragraph.</p>
<button onclick="toggleClass()">Toggle Highlight</button>

<script>
function toggleClass() {
var paragraph = [Link]('paragraph');
[Link]('highlight');
}
</script>
</body>
</html>
DOM Manipulation : Creating and Appending Elements
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create and Append Elements</title>
</head>
<body>
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
</ul>
<button onclick="addItem()">Add New Item</button>

<script>
function addItem() {
var list = [Link]('myList');

var newItem = [Link]('li');


[Link] = 'New Item';

[Link](newItem);
}
</script>
</body>
</html>
DOM Manipulation : Removing Elements
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Remove Elements</title>
</head>
<body>
<div id="container">
<p id="itemToRemove">This item will be removed.</p>
</div>

<button onclick="removeItem()">Remove Item</button>

<script>
function removeItem() {
var item = [Link]('itemToRemove');
[Link](item);
}
</script>
</body>
</html>
Event Handling
Event Handling

▪ Event handling allows JavaScript to respond to user actions.


▪ It makes web pages interactive — code runs when specific events happen.

Common Examples

Event type Example


Mouse click User clicks a button
Keyboard press User types a key
Form submission User submits a form
Page loading Browser finishes loading
Event Handling (Contd.)

▪ Event handling allows JavaScript to respond to user actions.


▪ It makes web pages interactive — code runs when specific events happen.

Common Examples Common Events

Event type Example Event Description


Mouse click User clicks a button onclick Mouse click on an element
Keyboard press User types a key onchange Value changed (input/select)
Form submission User submits a form onkeyup Key released on keyboard
Page loading Browser finishes loading onsubmit Form submitted
onload Page fully loaded
Event Handling: onclick — Mouse Click
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>onclick Event</title>
</head>
<body>
<h2>onclick Event — Mouse Click</h2>
<p>Click the button to trigger an alert.</p>

<button onclick="showMessage()">Click Me</button>

<script>
function showMessage() {
alert("Hello!");
}
</script>
</body>
</html>
Event Handling: onchange — Value Changed
....
<title>onchange Event</title>
</head>
<body>
<h2>onchange Event — Value Changed</h2>
<p>Select a car from the list. When you change the selection, the text updates.</p>

<select id="carSelect" onchange="updateText()">


<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes">Mercedes</option>
</select>

<p id="result"></p>

<script>
function updateText() {
const selected = [Link]("carSelect").value;
[Link]("result").innerHTML = "You selected: " + selected;
}
</script>
</body>
....
Event Handling: onkeyup — Key Released
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>onkeyup Event</title>
</head>
<body>
<h2>onkeyup Event — Key Released</h2>
<p>Type in the box. Every time you release a key, the message updates.</p>

<input type="text" id="nameInput" onkeyup="updateInput()" placeholder="Type your name"


/>

<p id="result"></p>

<script>
function updateInput() {
const value = [Link]("nameInput").value;
[Link]("result").innerHTML = "You typed: " + value;
}
</script>
</body>
</html>
Event Handling: onsubmit — Form Submitted
....
<body>
<h2>onsubmit Event — Form Submitted</h2>
<p>Enter your mobile number and click Submit.</p>

<form onsubmit="showSubmitMessage()">
<label>Mobile Number:</label>
<input type="text" name="mobile" required />
<br /><br />
<input type="submit" value="Submit" />
</form>

<script>
function showSubmitMessage() {
alert("Mobile number received! We will revert you.");
// Prevent actual form submission (optional for demo)
return false;
}
</script>
</body>
</html>
Event Handling: onload — Page Loaded
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>onload Event</title>

<script>
function pageLoaded() {
alert("This page has been successfully loaded!");
[Link] += "<p style='color:green; font-weight:bold;’>Page loaded
successfully!</p>";
}
</script>
</head>
<body onload="pageLoaded()">
<h2>onload Event — Page Loaded</h2>
<p>This page triggers an alert when it finishes loading.</p>
</body>
</html>
Event Handling: addEventListener() — Modern
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>addEventListener onclick</title>
</head>
<body>
<h2>addEventListener() — Modern Click Event</h2>
<p>Click the button using addEventListener (recommended method).</p>

<button id="myButton">Click Me</button>

<script>
const btn = [Link]("myButton");

[Link]("click", function() {
alert("Hello (from addEventListener)!");
});
</script>
</body>
</html>
Forms
Forms
▪ Forms are HTML elements used to collect data from users.
▪ JavaScript can access, validate, and process form data before it is
submitted to the server.

▪ Common Form Controls ▪ Importance


▪ Text Box ▪ User registration

▪ Password Box ▪ Login systems

▪ Radio Button ▪ Data collection

▪ Checkbox ▪ Surveys
▪ Select Menu

▪ Submit Button
Form Processing Steps

User Input

Read Values

Validate Data

Submit Form
<body>
<h2>Greeting Generator</h2>

<label for="firstName">First Name:</label>


<input type="text" id="firstName" placeholder="Enter your first name">
<br><br>

<label for="lastName">Last Name:</label>


<input type="text" id="lastName" placeholder="Enter your last name">
<br><br>

<button onclick="generateGreeting()">Say Hello</button>


<p id="greetingMessage"></p>

<script>
function generateGreeting() {

const firstName = [Link]("firstName").value; // Get the text value for firstName


const lastName = [Link]("lastName").value; // // Get the text value for firstName

const displayArea = [Link]("greetingMessage");

if ([Link]() !== "" && [Link]() !== "") {


[Link] = "Hello, " + firstName + " " + lastName + "!";
} else {
[Link] = "Please enter both your first and last name.";
}
}
</script>
</body>
Cookies
Cookies

▪ Cookies are small pieces of data stored by a web browser at the


request of a web server. They help websites remember user
information and maintain state between requests.
▪ Uses
▪ Session Management
▪ Authentication
▪ User Preferences
▪ Shopping Carts
▪ Tracking and Analytics
Cookie Component
username=John; expires=Fri, 31 Dec 2027; path=/

Components
Attribute Component Core Structural Purpose Technical Execution Behavior
Encoded sequence key value parameters. Must be explicitly
Name=Value The Data Payload
URL-encoded via script execution handles.

Expires relies on explicit UTC timestamps.


Expires / Max-Age Lifecycle Control Max-Age sets absolute delta offsets in remaining runtime
seconds.

Explicitly sets matching host origins authorized to handle


Domain Host Boundary Scope
storage values (e.g., domain=[Link]).

Isolates delivery patterns to sub-routes matching explicit URL


Path Sub-directory Scope
paths (e.g., path=/secure/dashboard).
Creating Cookies

Syntax Example

[Link] = "name=value"; [Link] = "username=John";


Reading Cookies

Syntax and Implementation

[Link];
Deleting Cookies

Syntax and Implementation

[Link] = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";


Working with Local Storage
Local storage stores data on the client side and it persistent across page
reloads. //Save data to local storage

[Link]('name', 'John Doe');


[Link]('age', '30');
Methods:
//Retrieve data from local storage
▪ [Link]()
const name = [Link]('name');
▪ [Link]() const age = [Link]('age');
[Link](`Name: ${name}, Age: ${age}`);
▪ [Link]()
▪ [Link](); //Remove data from local storage

[Link]('name');

//Clear all data from local storage

[Link]();
Local storage VS Cookies
Cookies
Local Storage

▪ Data is sent to the server with


▪ Data is stored on the client
every HTTP request made to the
side and is not sent to the
domain.
server with each HTTP request.

▪ This can impact performance


▪ It is only accessible via
and is often used for server-side
JavaScript running on the
session management or tracking.
same domain.
Handling Regular Expressions
Regular Expressions
▪ A Regular Expression (regex or regexp) is a sequence of
characters that defines a search pattern and used for string
matching, validating, searching, and manipulating text.
▪ Applications
▪ Email Validation
▪ Password Validation
▪ Search and Replace
▪ Pattern Matching
▪ JavaScript supports regex via literal /pattern/ or new RegExp().
Regex Components

Symbol Meaning Example


^ Start of string ^abc
$ End of string abc$
. Any character a.c
* Zero or more ab*c
+ One or more ab+c
? Optional ab?c
[ ] Character set [a-z]
{n} Exactly n times \d{10}
() Grouping (abc)
` ` OR

Flags (after the pattern): g – global, i – case insensitive, m – multiline


Implementation Logic

User Input Syntax:



/pattern/
Regex Pattern [Link](text);

Pattern Match Example:
↓ let pattern = /abc/;
Valid / Invalid [Link]("abc"); //true
Examples Email Validation
let pattern = /^[a-zA-Z0-9._%+-]+ @[a-zA-Z0-9.-]+ \.[a-
zAZ]{2,}$/;
let email = "student@[Link]";

[Link]([Link](email)); // true

Phone Number Validation

let pattern =/^[0-9]{10}$/;

let pattern = /^\d{10}$/;

Password Validation
let pattern =/.{8,}/;
let pattern = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/
Regex Methods
let str = "Contact: 9876543210";
let phonePattern = /\d{10}/;

// 1. test()
[Link]([Link](str)); // true

// 2. match()
[Link]([Link](phonePattern)); // ["9876543210"]

// 3. replace()
let newStr = [Link](phonePattern, "**********");
[Link](newStr);

Tip: Always test regex with multiple inputs (valid + invalid cases).
Validating Regular Expression
Client-Side Validation
Client-Side Validation
▪ Client-side validation is the process of verifying user input in the browser
before the data is submitted to the server.

▪ Advantages: User Input


▪ Improve user experience ↓
Validation Rules
▪ Reduce server load ↓
Valid ?
▪ Prevent invalid data submission ┌────┴────┐
▪ Provide immediate feedback Yes No
↓ ↓
Submit Error Message

Fig: Validation Workflow


Common Validation Rules
Validation Rules
Required Field Must not be empty
Email Validation Correct email format
Length Validation Minimum/Maximum length
Numeric Validation Numbers only
Range Validation Value within limits

Validation Workflow
User Input

Read Values

Apply Rules

Show Error / Submit
<!DOCTYPE html>
<html>
<head>
<title>Client-Side Form Validation</title>
</head>
<body>

<h2>Registration Form</h2>

<form onsubmit="return validateForm()">

<label>Name:</label><br>
<input type="text" id="name"><br><br>

Example 1
<label>Email:</label><br>
<input type="text" id="email"><br><br>

<label>Mobile Number:</label><br>
<input type="text" id="phone"><br><br>

<label>Password:</label><br>
<input type="password" id="password"><br><br>

<label>Confirm Password:</label><br>
<input type="password" id="confirmPassword"><br><br>

<input type="submit" value="Register">

</form>
<p id="message"></p>
<script>

function validateForm() {

let name = [Link]("name").value;


let email = [Link]("email").value;
let phone = [Link]("phone").value;
let password = [Link]("password").value;

let confirmPassword = [Link]("confirmPassword").value;

let emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

let phonePattern = /^[0-9]{10}$/;

if ([Link]() == "") {
[Link]("message").innerHTML = "Name cannot be empty.";
return false;
}

if (![Link](email)) {
[Link]("message").innerHTML = "Please enter a valid email address.";
return false;
}

if (![Link](phone)) {
[Link]("message").innerHTML = "Mobile number must contain exactly 10 digits.";
return false;
}

if ([Link] < 8) {
[Link]("message").innerHTML = "Password must be at least 8 characters long.";
return false;
}
if (password != confirmPassword) {
[Link]("message").innerHTML = "Passwords do not match.";
return false;
}

[Link]("message").innerHTML = "Registration Successful!";

return false;
}

</script>

</body>
</html>
Example 2

//[Link]

<form id="regForm" onsubmit="return validateForm(event)">


<input type="text" id="name" placeholder="Full Name" required>
<span id="nameError" class="error"></span><br>

<input type="email" id="email" placeholder="Email">


<span id="emailError" class="error"></span><br>

<input type="submit" value="Register">


</form>
Example 2 (Contd.)
[Link]

function validateForm(e) {
let isValid = true;
// Name validation
if ([Link]("name").[Link]() === "") {
[Link]("nameError").textContent = "Name is required";
isValid = false;
}

// Email validation with regex


let emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
if (![Link]([Link]("email").value)) {
[Link]("emailError").textContent = "Invalid email";
isValid = false;
}

if (!isValid) [Link]();
return isValid;
}
Example 2 (Contd.)

// [Link]

.error { color: red; font-size: 0.9em; }


[Link] { border: 2px solid red; }

You might also like