Unit I Client Side Scripting
Unit I Client Side Scripting
Client-Side Scripting
Introduction
Learning Objectives
After this unit students will be able to:
▪ Understand basics of client-side scripting with JavaScript
• Scripts are typically short programs that automate tasks or control the
behavior of software applications.
▪ Browser inconsistencies
▪ Performance issues
▪ Client dependency
requests.
▪ Faster Responses
round trip.
Why Use Client-Side Scripting?
Why Use Client-Side Scripting?
Client-Side Scripting vs Server-Side Scripting
▪ Security Concerns:
security vulnerabilities.
▪ Browser Compatibility:
▪ 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). }
▪ Use template literals `Hello ${name}` instead of +Meaningful variable & function names
(camelCase)
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 (;).
/*
Increment counter by 1
*/
/**
* Calculate area of a rectangle
* @param {number} width - Rectangle width
* @param {number} height - Rectangle height
* @returns {number} The area of the rectangle
*/
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.
<!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]
<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
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>
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
3. Always use const if the type should not be changed (Arrays and Objects).
▪ null
▪ undefined
▪ boolean
▪ number
▪ string
▪ Object
Data Types : Overview
Type Category Example
✓ Example
let name = "John";
Data Types: Boolean
▪ Stores true or false values.
✓ 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
✓ Syntax
let score;
let variableName;
[Link](score); // undefined
✓ Example [Link](typeof score); // undefined
[Link](score === undefined);// true
let score;
Data Types: Symbol
✓ Syntax
let variableName = Symbol("description");
✓ Example
const id = Symbol("userId");
Data Types: Bigint
▪ Introduced in ES2020.
✓ Example
✓ Syntax
const objectName = { const student = {
name: "Alice",
property: value
age: 20
}; };
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".
▪ Other Operators
▪ Type:
typeof, instanceof
▪ Bitwise
&, , ^, ~, <<, >>
▪ Comma
,
let x = 10, y = 20;
[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
}
2. if … else Statement
if (condition) {
// True block
Syntax } else {
// False block
}
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.
▪ 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.
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
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
city: "New York"
}
Accessing Array Data
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]();
indexOf(): Returns the first index at which a given element can be found
in the array, or -1 if it is not present.
[Link](index); // Output: 1
Iterating Over Arrays : For Loop
[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
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 greet(name) {
Function [Link]("Hello, " + name + "!");
with }
parameter
greet("Alice"); // Output: Hello, Alice!
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 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
Example:
const str = "Hello";
[Link]([Link](1)); // "e"
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"
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!"
Example:
const value = NaN;
[Link](isNaN(value)); // true
Date Objects
Date Functions
1) Current Date and Time
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()
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
▪ [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.)
<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>
<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
<script>
const frame = [Link]('iframe’);
[Link] = 'about:blank';
[Link](frame);
<!DOCTYPE html>
<html lang="en"> The DOM tree for this document would
</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
//JS
//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')
// JavaScript
var element = [Link]('.myClass');
▪ 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');
[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>
<script>
function removeItem() {
var item = [Link]('itemToRemove');
[Link](item);
}
</script>
</body>
</html>
Event Handling
Event Handling
Common Examples
<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>
<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>
<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>
<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.
▪ Checkbox ▪ Surveys
▪ Select Menu
▪ Submit Button
Form Processing Steps
User Input
Read Values
Validate Data
↓
Submit Form
<body>
<h2>Greeting Generator</h2>
<script>
function generateGreeting() {
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.
Syntax Example
[Link];
Deleting Cookies
[Link]('name');
[Link]();
Local storage VS Cookies
Cookies
Local Storage
[Link]([Link](email)); // true
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.
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>
<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>
</form>
<p id="message"></p>
<script>
function validateForm() {
if ([Link]() == "") {
[Link]("message").innerHTML = "Name cannot be empty.";
return false;
}
if () {
[Link]("message").innerHTML = "Please enter a valid email address.";
return false;
}
if () {
[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;
}
return false;
}
</script>
</body>
</html>
Example 2
//[Link]
function validateForm(e) {
let isValid = true;
// Name validation
if ([Link]("name").[Link]() === "") {
[Link]("nameError").textContent = "Name is required";
isValid = false;
}
if (!isValid) [Link]();
return isValid;
}
Example 2 (Contd.)
// [Link]