0% found this document useful (0 votes)
6 views49 pages

Module 2 Fsd Notes1

The document provides an overview of the Document Object Model (DOM) and its manipulation using JavaScript, covering topics such as accessing and updating elements, event handling, and form validation. It details the structure of the DOM tree, methods for selecting and modifying nodes, and different types of events that can be triggered by user interactions. Additionally, it emphasizes best practices for event handling, including the use of event listeners and event delegation for improved performance and maintainability.

Uploaded by

nsurabhi21
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)
6 views49 pages

Module 2 Fsd Notes1

The document provides an overview of the Document Object Model (DOM) and its manipulation using JavaScript, covering topics such as accessing and updating elements, event handling, and form validation. It details the structure of the DOM tree, methods for selecting and modifying nodes, and different types of events that can be triggered by user interactions. Additionally, it emphasizes best practices for event handling, including the use of event listeners and event delegation for improved performance and maintainability.

Uploaded by

nsurabhi21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

SJB Institute of Technology, Bangalore – 60

BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Name of the Course: FSD (BIS601)


NOTES – Module-2
Chapter 5,6,13
5- Document Object Model:
DOM Manipulation,
Selecting Elements,
Working with DOM Nodes,
Updating Element Content & Attributes,
6- Events-
Different Types of Events,
How to Bind an Event to an Element,
Event Delegation, Event Listeners.
13- Form Enhancement & validation
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Chapter 5

DOM (Document Object Model) specifies how browsers should create a model of an HTML page and
how the javascript can access and update the contents of a web page while it is in the browser window.

The DOM Tree is a Model of a Webpage

As a browser loads a web page, it creates a model of that page. The model is called a DOM tree, and it is
stored in the browsers’ memory. It consists of four main types of nodes.
<!DOCTYPE html>
<html>
<head>
<title>DOM Tree</title>
</head>
<body>
<h1 id="main-heading">Hello</h1>
<p class="intro">Welcome to the DOM.</p>
</body>
</html>

Every element, attribute, and piece of text in the HTML is represented by its own DOM node.

DOM Tree

Document (Root Node)

├── <html> (Element Node)

│ ├── <head> (Element Node)

│ │ ├── <title> (Element Node)

│ │ │ └── "DOM Tree" (Text Node)

│ ├── <body> (Element Node)


SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

│ │ ├── <h1 id="main-heading"> (Element Node)

│ │ │ ├── id="main-heading" (Attribute Node)

│ │ │ └── "Hello" (Text Node)

│ │ ├── <p class="intro"> (Element Node)

│ │ │ ├── class="intro" (Attribute Node)

│ │ │ └── "Welcome to the DOM." (Text Node)

Each node is an object with methods and properties. Scripts access and update this DOM tree (not the
source HTML file). Any changes made to the DOM tree are reflected in the browser.

The DOM tree consists of different types of nodes, arranged in a hierarchical manner:

1. Document Node

o The root of the tree, representing the entire document (document object in JavaScript).

2. Element Nodes

o Represent HTML elements (<html>, <head>, <body>, <h1>, <p>, etc.).

o Can have child elements (nested tags).

3. Attribute Nodes

o Represent attributes of elements (like class, id, src in <img src="image.jpg">).

o These are associated with element nodes but do not appear as children.

4. Text Nodes

o Contain the actual text inside elements.

o Example: “hello”, “welcome to the DOM”.


SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

DOM Manipulation

The Document Object Model (DOM) represents web page elements as nodes. When working with
the DOM, you interact with these nodes to access, modify, and manage elements. DOM
manipulation involves changing the structure, style, or content of a webpage dynamically using
JavaScript.

Step 1:

Accessing Elements –

Selecting Individual Elements, Selecting Multiple Elements, Traversing Elements.

Step 2:

Working with Elements –

Modify Text Content, Add or Remove Elements, Update Attributes

There are several methods to access elements in the DOM. These can be grouped into:

Step 1: access the elements

1. Selecting individual elements

2. Selecting multiple elements (NodeLists)

3. Traversing between elements in the DOM tree

1. Selecting an Individual Element Node

You can select a single element using these methods:

Method Description Example

getElementById() Selects an element by its unique id. document.getElementById("header");

Selects the first element that matches a CSS


querySelector() document.querySelector(".content");
selector.

Note:
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

• getElementById() is faster but only works with id attributes.

• querySelector() is more flexible since it uses CSS selectors.

2. Selecting Multiple Elements (NodeLists)

You can select multiple elements at once using these methods:

Method Description Example

Selects all elements with a


getElementsByClassName() document.getElementsByClassName("box");
given class.

Selects all elements with a


getElementsByTagName() document.getElementsByTagName("p");
specific tag name.

Selects all elements


querySelectorAll() document.querySelectorAll("div.container");
matching a CSS selector.

Note:

• getElementsByClassName() and getElementsByTagName() return live collections, meaning they


update when the DOM changes.

• querySelectorAll() returns a static NodeList that does not update dynamically.

3. Traversing Between Element Nodes

Once you have selected an element, you can navigate the DOM tree to find related elements.

Property/Method Description Example

Selects the parent node of an


parentNode document.getElementById("child").parentNode;
element.

previousSibling / Selects the previous or next


document.getElementById("item").nextSibling;
nextSibling sibling element.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Step 2: work with those elements

Once you have selected elements, you can:

1. Access or update text content inside an element.

2. Modify the HTML structure by adding or removing elements.

3. Update attributes of an element.

Access / update text nodes

Text inside an element is stored in a text node. To access it:

1. Select the <li> element (or any other element).

2. Use the .firstChild property to get its text node.

3. Use the nodeValue property to get or update the text content.

Working with an HTML content.There are two key properties to manipulate content inside elements:

Property Description
innerHTML Returns or updates the HTML content inside an element (including child elements).
textContent Returns or updates only the text inside an element, ignoring any HTML tags.

Creating and Removing Elements

The following methods allow you to dynamically create, add, or remove elements from the DOM:

Method Description

createElement() Creates a new element.

createTextNode() Creates a new text node.

appendChild() Adds a new node as the last child of an element.

removeChild() Removes a child element.


SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Update attribute values

Attributes provide additional information about an element. You can get, update, or remove attributes
using the following properties and methods:

Method / Property Description

className / id Gets or updates the class and id attributes.

hasAttribute() Checks if an attribute exists.

getAttribute() Gets the value of an attribute.

setAttribute() Updates or adds a new attribute.

removeAttribute() Removes an attribute.

mouseout Fires when the mouse leaves an element.

Selecting Elements
To manipulate elements, you first need to select them. JavaScript provides several methods for
selecting elements.
Methods:
• getElementById()
• getElementsByClassName()
• getElementsByTagName()
• querySelector()
• querySelectorAll()
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

• getElementById()
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

• getElementsByClassName()

In Literal & Constructor


SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

• getElementsByTagName()

• querySelector() & querySelectorAll()

Looping through a Nodelist


SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Traversing an element – Previous & Next Sibling

First & Last Child


SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Working with DOM Nodes


1. Accessing Nodes
2. Creating and Adding Nodes
3. Modifying Nodes
4. Removing Nodes

1. Accessing Nodes - textcontent & innerHTML

You can access nodes using different methods.

2. Creating and Adding Nodes - create element, create text node, append child

You can dynamically create and insert new nodes


SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

3. Modifying Nodes

You can modify text, attributes, or elements.

4. Removing Nodes
1. Store the element to be removed in a variable,
2. store the parent of that element in a variable,
3. Remove the element from its containing element
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Updating a Element Content & Attribute


Method Modifies Use Case

Add or update HTML inside an


innerHTML HTML content
element

Change text content (ignores


innerText Text only
hidden text)

Change text content (includes


textContent Text only
hidden text)

Value Input field value Update form input fields


appendChild() New element Add new elements dynamically

Attribute

Syntax
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

1. Check for an attribute and get its values

2. Creating attributes and changing their values

3. Removing attributes

1. Check for an attribute and get its values


SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

2. Creating attributes and changing their values

3. Removing attributes
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Chapter 6 - Event

Different Types of DOM Events


The DOM events are actions that can be performed on HTML elements. When an event occurs, it triggers
a javascript function.
This function can then be used to change the HTML element or perform other actions.
1. UI Events –
Occur when a user interacts with the browser's user interface (UI) rather than the web page.
2. Keyboard Events –
Occur when a user interacts with the keyboard.
3. Mouse Events –
Occur when a user interacts with a mouse, trackpad, or touchscreen.
UI Events

Keyboard Events
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Mouse Events

Example:
// Log a key press
document.addEventListener("keydown", function(event) {
console.log("Key pressed: " + event.key);
});

How to Bind an Event to an Element


Event handlers allow us to specify actions that should occur when a user interacts with an element (e.g.,
clicking a button, hovering over a link, typing in a form). There are three primary ways to bind events in
JavaScript:
1. HTML Event Handlers (Old and Deprecated)
This method directly embeds JavaScript into the HTML element using event attributes like onclick,
onmouseover, onblur, etc.
Example:

<a href="#" onclick="hide()">Click me</a>


Here, the onclick attribute calls the hide() function when the <a> element is clicked.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

<input type="text" id="username" onblur="checkUsername()" />


• The onblur attribute runs checkUsername() when the user leaves the input field.
• If the username is too short, an error message is displayed.

Instead of using inline event handlers, you should use JavaScript event listeners.

2. Traditional DOM Event Handlers

Separates JavaScript from HTML. It is supported in all major browsers. But can only attach one function
per event. Assigning another function will overwrite the previous one.

Syntax
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

JavaScript selects an element and assigns a function to its event property.

3. DOM Level 2 Event Listeners (Best Practice)


Introduced in DOM Level 2 (Year 2000). It allows multiple event listeners for the same event.
In this no function overwriting and better separation of concerns. It Works well with modern frameworks
like jQuery.
Note:

Method Pros Cons

Bad practice, mixes HTML & JS, hard to


HTML Event Handlers Simple, works in old browsers
maintain

Traditional DOM Cleaner separation of JS and Only one event per element (overwrites
Handlers HTML existing handlers)

DOM Level 2 Event Best practice, allows multiple


Not supported in IE8 or older
Listeners handlers

Always use addEventListener() for event handling unless supporting very old browsers.
Avoid inline HTML event handlers and traditional onevent handlers to keep your code clean and
maintainable.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Event Listeners
Event listeners are the modern and preferred way to handle events in JavaScript. They allow multiple
event handlers to be assigned to a single event on an element, unlike traditional event handlers, which only
support one function per event.

Syntax

The addEventListener() method takes three properties:

i) The event you want it to listen for. In this case, the blur event.

ii) The code that you want itto run when the event fires.In this example, it is the checkUsername()
function.

(Note that the parentheses are omitted where the function is called because they would indicate that the
function should run as the page loads (rather than when the event fires)).

iii) A Boolean indicating how events flow,(This is usually set to false.)


SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Using Parameter with Handlers & Listener

Because you cannot have parentheses after the function names in event handlers or listeners, passing
arguments requires a workaround.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Event Listener with parameter and with no parameter

Features Without Parameters With Parameters(checkUsername(e,


(checkUsername) minLength))

How function
Directly as checkUsername Inside an anonymous function
is passed?

How event (e) Automatically by JavaScript Manually inside the anonymous function
is passed?

Can you pass No Yes(like minLength)


extra
arguments?
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Note:
Event listeners (addEventListener()) are the recommended way to handle events in JavaScript because:
1. They allow multiple functions to be attached to a single event.
2. They keep JavaScript separate from HTML, improving maintainability.
3. They provide better flexibility in event management.

Event Delegation
Event delegation is a technique in JavaScript where you attach an event listener to a parent (or ancestor)
element instead of adding separate event listeners to multiple child elements. This improves performance,
simplifies code, and ensures that dynamically added elements also receive event handling.

Why Use Event Delegation?


1. Performance Optimization
o Adding event listeners to each individual element (like multiple buttons, list items, or table
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

cells) can slow down a webpage.


o Instead, placing one event listener on a parent element reduces memory usage and speeds up
execution.
2. Handles Dynamic Elements
o If new elements are added to the DOM dynamically (e.g., via JavaScript), you don’t need to
manually attach event listeners to them.
o The event listener on the parent element will automatically handle events from newly added
elements.
3. Simplifies Code
o With fewer event listeners, the code becomes more readable and maintainable.

How Event Delegation Works


• Events in JavaScript follow event bubbling:
When an event occurs on an element, it first triggers on that element and then propagates up to its
ancestors.
• By placing an event listener on a parent element, you can use the event object’s target property to
determine which child element triggered the event.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

// Add a click event listener to a parent element


document.getElementById("parent").addEventListener("click", function(event) {
if (event.target && event.target.matches("button.className")) {
console.log("Button clicked: " + event.target.textContent);
}
});

Creating event listeners for a lot of elements can slow down a page, but event flow allows you to listen for
an event on a parent element
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Chapter 13 - Form Enhancement & Validation

Forms and JavaScript

Forms in HTML allow websites to collect user information, such as login details, feedback, or payment
details. JavaScript helps improve this process by:

Enhancing forms to make them more interactive and user-friendly.

Validating input to ensure users provide correct and complete information before submission.

Three Main Aspects Covered in This Chapter

This chapter is divided into three sections:

a) Form Enhancement

JavaScript improves user experience by adding interactive features like auto-complete, dynamic field
updates, and error highlighting.

Enhancements help users fill out forms more efficiently and reduce errors.

b) HTML5 Form Elements

HTML5 introduced new form elements like <input type="email">, <input type="date">, and <datalist>.

These elements help improve validation without needing extra JavaScript.

c) Form Validation

Ensures users provide correct data before submitting.

JavaScript checks for missing or incorrect input and provides instant feedback.
Example: Checking if an email address is in the correct format before allowing submission.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Helper Functions in JavaScript for Event Handling

This section is about creating helper functions to handle events across different browsers, particularly
dealing with older versions of Internet Explorer (IE5-8). Let's break it down:

1. What Are Helper Functions?

Helper functions are reusable pieces of code that simplify tasks.

Instead of writing the same code multiple times, you write it once in a function and reuse it.

In this case, the helper function helps handle events in a way that works across all browsers.

2. Why Do We Need This Helper Function?

Different browsers handle events differently.

Modern browsers use addEventListener(), while older Internet Explorer versions (IE5-8) use
attachEvent().

Instead of writing separate event-handling code for each browser, we create a single function that works
for all.

3. The addEvent() Helper Function


This function helps attach event listeners to elements in a cross-browser way.
function addEvent(el, event, callback) {
if ('addEventListener' in el) {
el.addEventListener(event, callback, false); // Modern browsers
} else {
el['e' + event + callback] = callback;
el[event + callback] = function() {
el['e' + event + callback](window.event); // Pass event object in old IE
};
el.attachEvent('on' + event, el[event + callback]); // IE fallback
}
}
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Note:

1. The function takes three parameters:

el → The element where the event should be attached.

event → The type of event (e.g., "click", "mouseover").

callback → The function to execute when the event occurs.

2. Checks if addEventListener() is supported:

If el has addEventListener, it is used (works for modern browsers).

3. If addEventListener() is not supported (Old IE 5-8):

Stores the callback function as a property of the element (el['e' + event + callback]).

Creates another function (el[event + callback]) to handle the event.


Uses attachEvent('on' + event, el[event + callback]) to attach the event in older IE
versions.

Form Element
The <form> element in HTML is special because it contains from controls(like
<input>,<select>,<textarea>, etc), and it has unique properties, methods, and events in the DOM.
1. Form properties
Forms have several properties that make them easy to access and manipulate.

Property Description
action The URL where the form data will be sent when submitted.
name Rarely used today. Instead, forms are usually selected by id.
A collection (like an array) of all form controls inside the form. Elements can be accessed by
elements
index number or name attribute.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Example:

// Access the second form on the page


let secondForm = document.forms[1];
2. Form methods
Forms have built-in methods to handle common actions.
Method Description
submit() Submits the form (same as clicking the submit button).
reset() Resets the form to its original values.
let myForm = document.getElementById("contactForm");
// Programmatically submit the form
myForm.submit();
// Reset the form fields to default values
myForm.reset();
3. Form events
Forms trigger special events when users interact with them.

Event Description
submit Fires when the form is submitted.
Reset Fires when the form is reset.

let myForm = document.getElementById("contactForm");


myForm.addEventListener("submit", function(event) {
event.preventDefault(); // Prevents the form from submitting
console.log("Form submission prevented.");
});
Form Control
1. These properties allow interaction with and manipulation of form elements.

Property Description

Value Holds user input for text fields; otherwise, it reflects the value attribute.

Type Specifies the type of an <input> element (e.g., text, password, radio, checkbox).
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Property Description

Name Gets or sets the name attribute of an input field.

defaultValue The initial value of a text box or text area when the page loads.

Form Refers to the <form> element that the input belongs to.

Disabled Disables the form element, preventing user interaction.

Checked Boolean (true/false) indicating whether a checkbox or radio button is selected.

Boolean reflecting whether a checkbox or radio button was checked when the page
defaultChecked
loaded.

Selected Boolean indicating if an item in a <select> dropdown is selected.


2. Methods for Form Controls
Methods allow programmatic interaction with form elements.

Method Description

focus() Moves the cursor into the input field.

blur() Removes focus from the field.

select() Highlights text inside a text input or password field.

Simulates a user clicking a button, checkbox, or file upload input. It also triggers a submit
click()
event when called on a submit button and a reset event on a reset button.

3. Common Events in Form Controls


Events allow scripts to respond to user interactions with form elements.

Event Description

Blur Triggered when the user moves away from an input field.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Event Description

Focus Triggered when the user enters a field.

Click Triggered when a button or checkbox is clicked.

Triggered when an input's value changes (e.g., selecting a new dropdown


Change
option).

Input Triggered when the user types in an <input> or <textarea> field.

keydown, keyup,
Triggered when a user interacts with the keyboard.
keypress

Submitting Forms
Explaining the Steps for Handling Form Submission Using JavaScript.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

1. The script is wrapped inside an IIFE to avoid global variable pollution.

2. The <form> element is selected and stored in a variable.

3. An event listener is added to detect when the form is submitted.

4. preventDefault() stops the page from refreshing.

5. The form elements collection is accessed.

6. The username input value is retrieved.

7. A welcome message is dynamically created.


8. The form's inner HTML is updated to show the welcome message instead.
1. (function () {
// Select the form element
2. var form = document.querySelector("form");
// Add an event listener for form submission
3. form.addEventListener("submit", function (event) {
4. event.preventDefault(); // Prevent the default form submission behavior
// Get all form elements
5. var elements = form.elements;
// Retrieve the username input value
6. var username = elements["username"].value;
// Create a welcome message
7. var msg = "<h2>Welcome, " + username + "!</h2>";
// Replace the form with the welcome message
8. form.innerHTML = msg;
});
})();
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Changing Type of Input (Check box)

1. Place the script in an IIFE (Immediately Invoked Function Expression)

The script is wrapped inside an IIFE to avoid polluting the global scope.

This ensures the code runs immediately after being loaded.

2. Put password input and checkbox in variables

Select and store the password input field and checkbox elements using document.querySelector().

3. An event listener triggers an anonymous function when the show password checkbox is changed

A change event listener is attached to the checkbox.

When the user toggles the checkbox, the function runs.

4. The target of the event (the checkbox) is stored in a variable called target
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

The event.target property refers to the checkbox that was clicked.

Older versions of Internet Explorer (IE) used event.srcElement, but modern browsers support
event.target.

5. A try...catch statement checks if an error occurs when changing the type attribute

Some browsers may not allow changing the type attribute dynamically.

Wrapping the code inside try...catch ensures errors are handled gracefully.

6. If the checkbox is selected:

The script checks if the checkbox is checked (true or false).

7. The value of the password input's type attribute is set to text

If the checkbox is checked, the password field becomes a text field, making the password visible.

8. Otherwise, it is set to password

If the checkbox is unchecked, the password field returns to hidden mode.

9. If trying to change the type causes an error, the catch clause runs

If an error occurs when changing the type, the catch block handles it.

10. It shows a message to inform the user


Instead of breaking the script, an error message is displayed to the user.
(function () {
// Select the password input and checkbox elements
var passwordInput = document.querySelector("#password");
var showPasswordCheckbox = document.querySelector("#showPassword");
// Add an event listener for checkbox change
showPasswordCheckbox.addEventListener("change", function (event) {
var target = event.target; // Get the checkbox
try {
// If checkbox is checked, show password; otherwise, hide it
passwordInput.type = target.checked ? "text" : "password";
} catch (error) {
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

// Handle errors (for very old browsers that don't support changing input type)
alert("Sorry, your browser does not support changing password visibility.");
}
});
})();

Note:

1. The checkbox is clicked.

2. The event listener detects the change.

3. If the checkbox is checked, the password becomes visible.

4. If the checkbox is unchecked, the password is hidden again.


5. If the browser does not support changing the input type, an error message is displayed.

Radio Button
1. Place the script in an IIFE (Immediately Invoked Function Expression)
The script is enclosed in an IIFE to avoid polluting the global scope.
This ensures the code runs automatically once the page loads.
2. Set up variables for form elements
The script starts by defining variables to hold:
The form
The collection of radio buttons
The "Other" radio button
The text input field (which will be shown or hidden)
3. Hide the text input initially
JavaScript updates the class attribute of the text input field to hide it.
This ensures the form still works for users without JavaScript.
4. Use a for loop to attach event listeners to radio buttons
The script loops through all radio buttons and adds an event listener to each.
When a radio button is clicked, the radioChanged() function is called.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

5. Declare the radioChanged() function


This function is triggered whenever a radio button is selected.
6. Check if the "Other" option is selected
If the "Other" radio button is checked:
The hide variable is set to a blank string (""), making the text input visible.
Otherwise:
The hide variable is set to "hide", keeping the text input hidden.
7. Apply the hide variable to the text input’s class attribute
If hide is an empty string (""), the text input is shown.
If hide contains "hide", the text input is hidden.
8. Clear the text input when hiding
If the text input is hidden, its content is cleared to ensure it is empty when shown again.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Select Boxes
A <select> element in HTML is a dropdown menu that allows users to choose from multiple options. It
consists of multiple <option> elements representing the available choices.
Key Properties of <select>
1. options – Collection of all <option> elements inside the <select>.
2. selectedIndex – The index of the currently selected option (starts from 0).
3. length – The total number of options.
4. multiple – If set to true, users can select multiple options.
5. selectedOptions – Collection of all selected <option> elements.

Key Methods
1. add(option, before)
o Adds a new option to the list.
o The first parameter is the new <option>, and the second is the position where it should be
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

inserted.
2. remove(index)
o Removes an option from the list based on its index.
<label for="equipmentType">Type:</label>
<select id="equipmentType" name="equipmentType">
<option value="choose">Please choose a type</option>
<option value="cameras">Camera</option>
<option value="projectors">Projector</option>
</select>
<br>
<label for="model">Model:</label>
<select id="model" name="model">
<option>Please choose a type first</option>
</select>
<input id="submit" type="submit" value="Submit" />
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

1. Place the script in an IIFE (not shown in flowchart).

2. Variables hold the two select boxes.

3. Two objects are created; each one holds options used to populate the second select box (one has types
of cameras, the other has types of projectors).

4. When the user changes the first select box, an event listener triggers an anonymous function.

5. The anonymous function checks if the first select box has a value of choose.

6. If so, the second select box is updated with just one option, which tells the user to select a type.

7. No further processing is needed, and the return keyword exits the anonymous function (until the user
changes the first select box again).

8. If a type of equipment has been selected, the anonymous function continues to run, and a models
variable is created. It will store one of the objects defined in step 3 (cameras or projectors). This correct
object is retrieved using the getModels() function declared at the end of the script (9410), The function
takes one parameter this.value, which corresponds to the value from the option that was selected in first
select box.

9. Inside the getModels() function, an if statement checks if the value passed in was cameras; if so, it
returns the cameras object.

10. If not, it continues to run, checking to see if the value was projectors, and if so, it returns the projectors
object.

11. A variable called options is created. It will hold all the <option> elements for the second select box.
When this variable is created the first <option> is added to it; it tells users to choose a model.

12. A for loop goes through the contents of the object that was placed in the models variable in step (8-
10). Inside the loop, key refers to the individual items in the object.
13. Another <option> element is created for every item in the object. Its value attribute uses the property
name from the object. The content that sits between the <option> tags is that property's value.
14. The options are then added to the second select box using the innerHTML property.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

TextArea
When the cursor is in the textarea, a <span> element will be shown with a count of how many characters
the user has remaining. When the textarea loses focus, this message is hidden.

1. Place the script in an IIFE (not shown in flowchart).


2. The script sets up two variables to hold: a reference to the <textarea> element and a reference to the
<span> that holds the message.
3. Two event listeners monitor the <textarea>. The first checks for when the element gains focus; the
second checks for a input event. Both events trigger a function called updateCounter() (6-11) The input
event does not work in IE8, but you can use keyup to support older browsers.
4. A third event listener triggers an anonymous function when the user leaves the <textarea>.
5. If the number of characters is less than or equal to 140 characters, the length of the bio is okay, and it
hides the message (because it is not needed when the user is not interacting with the element).
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

6. The updateCounter() function is declared.


7. It gets a reference to the element that called it.

8. A variable called count holds the number of characters left to use (it does this by subtracting the number
of characters used from 140).
9.if... else statements are used to set the CSS class for the element that holds the message (these can also
show the message if it was hidden).
10. A variable called charMsg is created to store the message that will be shown to the user.
11. The message is added to the page
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Submit Select Box


Feature Checkbox Radio Button Text Area
Button (Dropdown)
Allows one Allows selection of
Submits a Allows multiple Allows multi-
Purpose selection from one or more options
form selections line text input
a group from a list
No (Once
No (Can modify
Toggle No (Click Yes selected, No (Must have an
text but not
Behavior? = Submit) (Check/Uncheck) cannot option selected)
toggle)
unselect)
Can Select Yes (if multiple is Yes (User types
No Yes No
Multiple? enabled) freely)
Default
submit Change change change input / change
Event
Click to select
User Click Click to Click and select from
(cannot Type text
Interaction button check/uncheck options
deselect)
Login,
Example Agree to Terms, Gender Enter Feedback,
Contact Choose Country
Usage Toggle Features Selection Comments
Form
Reset Resets Selects default Selects first/default
Uncheck box Clears text
Behavior form fields radio button option
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

HTML5 Elements & Attributes


HTMLS adds form elements and attributes to perform tasks that had previously been performed by
JavaScript. However, their appearance can vary a lot between different browsers (especially their error
messages).
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

PlaceHolder Fallback

The HTMLS placeholder attribute lets you put words in text inputs (to replace labels or to add hints about
what to enter). When the input gains focus and the user starts typing, the text disappears. But
it only works in modern browsers, so this script ensures that the user sees placeholder text in older browsers
too. It is a basic example of a polyfill.

1. Place the script in an IIFE (not shown in flowchart).

2. Check if the browser supports the HTML5 placeholder attribute, If it does, there is no need for the
fallback. Use return to exit the function.

3. Find out how many forms are on the page using the length property of the forms collection.

4. Loop through each <form> element on the page and call showP]aceholder() for each one, passing it the
collection of elements in that form.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

5. The showPlaceholder() function is declared,

6. A for loop runs through elements in the collection.

7. An if statement checks each element to see if the element has a placeholder attribute with a value.

8. If there is no placeholder attribute, continue tells it to go on to the next element. Otherwise, it:

9. Changes the text color to gray, and sets the value of the element to be the placeholder text.

10. An event listener triggers an anonymous function when the element gains focus.

11. If the current value of the element matches the placeholder text, the value is cleared (and color
changed to black).

12. An event listener triggers an anonymous function when the element loses focus.
13. If the input is empty, the placeholder text is added back in (and its color changed to gray).
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Form Validation
Validation checks if user input meets specific rules (e.g., a password must have at least 8 characters)
before submitting a form. we check user input when the form is submitted. Since users can submit a form
by pressing the "Submit" button or hitting Enter, validation is handled using the submit event, not the
button’s click event.

Why is Validation Important?


1. Ensures correct and usable data.
2. Provides instant feedback, reducing errors.
3. Saves server resources by preventing unnecessary requests.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

Types of Validation:
1. Client-Side Validation (Browser-Based) – Fast, done using HTML attributes or JavaScript.
• Example: <input type="email" required> ensures a valid email format.
2️. Server-Side Validation (Backend-Based) – More secure, prevents users from bypassing validation.
• Example: Django, PHP, or Node.js validating input before saving to a database.
Best Practice: Use both client-side and server-side validation for security and efficiency.

Handling Errors in Form Validation(Dealing with errors)


When errors are found during form validation, the script must:
1️.Prevent form submission to avoid incorrect data.

2️. Inform the user about what needs to be corrected.


If an error is found:
• The valid object updates the field status as invalid.
• The setErrorMessage() function stores the error message using jQuery’s .data() method.
After checking all fields:
• showErrorMessage() retrieves stored messages and displays them in a <span> element next to the
faulty input.
If the user fixes an error:
• The corresponding error message is removed, while other errors remain visible
Submitting the Form
Before sending the form, the script checks whether there were any errors. If there were, the script stops the
file from being submitted.

In order to check whether any errors were found, a variable called isFormValid is created and is given a
value of true. The script then loops through each property of the valid object, and if there was an error (if
any property of that object has a value of false), then there is an error in the form and the isFormValid
variable is also set to false.
So, isFormVal d is being used as a flag (you can think of it being like a master switch) if an error is found,
it is turned off. At the end of the script, if isFormValid is false then an error must have been found and the
form should not be submitted (using the preventDefault() method),
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING

It is important to check and process all of the elements before deciding whether to submit the form so that
you can show all of the relevant error messages in one go.

Custom Validation
The final part of the script performs three checks that apply to individual form elements; each check lives in
a named function.

Prepared By,
Prof. Ranjitha J,
Dept, of ISE
SJB Institute of Technology

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy