0% found this document useful (0 votes)
2 views

CSS Unit 3

Unit 3 focuses on form and event handling in HTML, detailing the structure and components of forms, including various input types and their attributes. It explains how to dynamically manipulate form elements and handle events like mouse and key actions. The document serves as a comprehensive guide for creating and managing forms in web development.

Uploaded by

Pallavi Deokar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

CSS Unit 3

Unit 3 focuses on form and event handling in HTML, detailing the structure and components of forms, including various input types and their attributes. It explains how to dynamically manipulate form elements and handle events like mouse and key actions. The document serves as a comprehensive guide for creating and managing forms in web development.

Uploaded by

Pallavi Deokar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Contents

Unit 3. Form and Event Handling .......................................................................................... 2

Forms .................................................................................................................................... 2

Building blocks of a form ................................................................................................ 2

Form Events ......................................................................................................................... 9

Mouse Events .................................................................................................................... 9

Key Events ........................................................................................................................ 9

Form Objects and Elements .............................................................................................. 12

Browser Object Model (BOM) ..................................................................................... 12

Changing Attribute Value Dynamically .......................................................................... 20

Changing Option List Dynamically .................................................................................. 21

Evaluating Checkbox Selection ........................................................................................ 21

Changing label dynamically .............................................................................................. 23

Manipulating Form Elements ........................................................................................... 24

Intrinsic JS Functions ........................................................................................................ 25

Disabling Element .............................................................................................................. 26

Read-Only Elements .......................................................................................................... 26


Unit 3. Form and Event Handling
Forms

 An html form is a section of a document which contains controls such as text fields,
password fields, checkboxes, radio buttons, menus, etc.
 An html form facilitates the user to enter data from/of the site visitor.
 Example: If a user wants to purchase some items on the internet, he/she must fill the
form such as shipping address and credit/debit card details so that the item can be sent
to the given address.
Building blocks of a form
1. The <form> element
 It provides a document section to take input from user.
 It provides various interactive controls for submitting information to the web server
such as text area, password field, etc.
 Attributes of the <form> tag:
Attribute Value Description
accept- Character-set Specifies the character encodings that are to be
charset used for the form submission.
<form action="action.js" accept-charset="utf-8">

action URL Specifies where to send the form-data when a


form is submitted.
<form action="action.html">
autocomplete on Specifies whether a form should have
off autocomplete on or off.
<form action="action.html" autocomplete="on">
<form action="action.html" autocomplete="off">
enctype application/x-www-form-urlencoded: All Specifies how the form-data should be encoded
characters are encoded before submitting the when submitting it to the server (only for
form. method="post")
multipart/form-data: Not encode any character. It <form action="action.html" method="post"
is used when our form contains file-upload enctype="application/x-www-form-urlencoded" >
controls. <form action="action.html" method="post"
text/plain: Sends data without encoding. enctype="multipart/form-data">
<form action="action.html" method="post"
enctype="text/plain">
target _blank: Opens the response in a new window or Specifies where to display the response that is
tab. received after submitting the form.
_self: Loads the response in the same frame or <form action="action.html" target="_self">
window (default). <form action="action.html" target="_blank">
_parent: Loads the response in the parent frame.
_top: Loads the response in the full body of the
window.
name text Specifies the name of a form
<form action="action.html" name="form1”>
method get: Appends the form data to the URL specified Specifies the HTTP method to use when sending
in the action attribute. It's typically used for form-data.
form submissions that do not change server state <form action="action.html" method="get”>
(e.g., search queries). But this is not secure as it <form action="action.html" method="post”>
displays data in URL after submitting the form.
post: Sends the form data as a message body. It's
used for form submissions that change server
state (e.g., submitting a form to update a
database).
rel external: Typically used to indicate that the Specifies the relationship between a linked
linked document is external to the site. Suggests resource and the current document.
that the link leads to an external resource, often <form action = "action.html" rel = "external" >
triggering a new browser window or tab. <form action = "action.html" rel = "help" >
help: Indicates that the linked document <form action = "action.html" rel = "license" >
provides help or assistance related to the current <form action = "action.html" rel = "next" >
context. Useful for linking to help pages, often <form action = "action.html" rel = "nofollow" >
within applications or documentation. <form action = "action.html" rel = "noopener" >
license: Specifies that the linked document is a <form action = "action.html" rel = "noreferrer" >
license governing the use of the current <form action = "action.html" rel = "prev" >
document. Typically used to point to a legal <form action = "action.html" rel = "search" >
license for the content or software.
next: Indicates that the linked document is the
next one in a series or sequence. Often used in
paginated content or documents divided into
multiple parts.
nofollow: Instructs search engines not to follow
the link to the linked document. Prevents passing
SEO value to the linked page, often used in user-
generated content or untrusted links.
noopener: Prevents the new page from being
able to access the window.opener property and
ensures that it runs in a separate process.
Improves security by preventing malicious pages
from gaining control over the originating page.
noreferrer: Similar to noopener, but it also
prevents the browser from sending a referrer
header. Enhances privacy by not revealing the
source of the traffic.
prev: Indicates that the linked document is the
previous one in a series or sequence. Often used
in navigation of paginated content or multi-part
documents.
search: Indicates that the linked document is a
search tool for the current document or site.
Points to a search interface or page related to the
current content.

2. The <input> element


 The html <input> element is a fundamental form element.
 It is used to create form fields, to take input from user.
 Attributes of the input tag:
1. type: Defines the type of data the input will accept.
Values of the type attribute:
Value Description Example
button A push button with no default behavior displaying the value of
the value attribute, empty by default.

checkbox A check box allowing single values to be selected/deselected.

color A control for specifying a color; opening a color picker when active in
supporting browsers.

date A control for entering a date (year, month, and day, with no time).
Opens a date picker or numeric wheels for year, month, day when
active in supporting browsers.
datetime- A control for entering a date and time, with no time zone. Opens a date
local picker or numeric wheels for date- and time-components when active in
supporting browsers.
email A field for editing an email address. Looks like a text input, but has
validation parameters and relevant keyboard in supporting
browsers and devices with dynamic keyboards.
file A control that lets the user select a file. Use the accept attribute to
define the types of files that the control can select.
hidden A control that is not displayed but whose value is submitted to the
server. There is an example in the next column, but it's hidden!

Value Description Example


image A graphical submit button. Displays an image defined by
the src attribute. The alt attribute displays if the image src is
missing.
month A control for entering a month and year, with no time zone.
number A control for entering a number. Displays a spinner and adds default
validation. Displays a numeric keypad in some devices with dynamic
keypads.
password A single-line text field whose value is obscured. Will alert user if site is
not secure.
radio A radio button, allowing a single value to be selected out of multiple
choices with the same name value.
range A control for entering a number whose exact value is not important.
Displays as a range widget defaulting to the middle value. Used in
conjunction min and max to define the range of acceptable values.
reset A button that resets the contents of the form to default values. Not
recommended.
search A single-line text field for entering search strings. Line-breaks are
automatically removed from the input value. May include a delete icon
in supporting browsers that can be used to clear the field. Displays a
search icon instead of enter key on some devices with dynamic
keypads.
submit A button that submits the form.

tel A control for entering a telephone number. Displays a telephone keypad


in some devices with dynamic keypads.
text The default value. A single-line text field. Line-breaks are
automatically removed from the input value.
url A field for entering a URL. Looks like a text input, but has validation
parameters and relevant keyboard in supporting browsers and
devices with dynamic keyboards.
week A control for entering a date consisting of a week-year number and a
week number with no time zone.
time A control for entering a time value with no time zone.

Other <input> element attributes:


Attribute Description Example
2. name The name of the input field, used to reference it in form data <input type="text"
(when submitted) and in JavaScript. name="username">
3. value Defines the default value for the input field. <input type="text"
value="John Doe">
4. placeholder A hint displayed in the input field when it's empty, <input type="text"
providing guidance on what to enter. placeholder="Enter your
name">
5. id Assigns a unique identifier to the input field, allowing it to <input type="text"
be easily targeted by CSS and JavaScript. id="userId">
6. required Specifies that the input field must be filled out before <input type="email" required>
submitting the form.
7. readonly Makes the input field read-only; the user can view the value <input type="text"
but cannot modify it. value="Read-only text"
readonly>
8. disabled Disables the input field, preventing user interaction and <input type="text" disabled>
making the input field appear faded.
9. maxlength Sets the maximum number of characters that can be entered <input type="text"
in a text-based input field. maxlength="10">
10. minlength Specifies the minimum number of characters required for <input type="text"
text input. minlength="5">
11. min and max Sets the minimum and maximum values for numeric inputs <input type="number" min="1"
max="100">
(number, date, range, etc.). <input type="date" min="2023-
01-01" max="2024-01-01">

12. step Specifies the legal number intervals for numeric inputs <input type="number"
(number, range). step="0.01"> (allows input in
steps of 0.01, such as 1.01, 1.02,
etc.)
13. pattern Specifies a regular expression pattern that the input value <input type="text"
must match. pattern="[A-Za-z]{3,}"> (only
allows letters, at least three
characters long).
14. autofocus Automatically focuses the input field when the page loads. <input type="text" autofocus>
15. autocomplete Controls whether the browser should provide suggestions <input type="text"
based on previous user inputs (on, off). autocomplete="on">
16. multiple Allows the user to select multiple values, applicable to <input type="file" multiple>
inputs like file and email.
17. size Specifies the width of the input field, measured in characters <input type="text" size="40">
(works for text input types).
18. accept Specifies the types of files that the server accepts (for file <input type="file"
accept=".png, .jpg, .jpeg">
input types).
19. list Associates the input field with a <datalist> element, <input type="text"
list="browsers">
allowing the user to select from predefined options.
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Safari">
</datalist>

20. form Associates the input with a specific form (useful when <input type="text"
form="form1">
inputs are not inside the <form> element).

3.The <textarea> element


 The <textarea> defines a form field to create a multiline input area.
 It is often used in forms to collect user inputs like comments or reviews.
 It can hold an unlimited number of characters, and the text renders in a fixed width font
(usually Courier).
 The size of a <textarea> is specified by ‘rows’ and ‘cols’ attributes.
 The ‘name’ attribute is needed to reference the form data after the form is submitted.
(If omitted, no data from the <textarea> will be submitted.)
 The ‘id’ attribute is needed to associate the <textarea> with a <label>.
 Syntax: <textarea rows = value cols = value>Enter Here</textarea>
4. The <button> element
 The <button> tag is used to place a button inside a form, which defines a clickable
button.
 Inside a <button> element, you can put text and tags like <b>, <u>, <i>, <img>, <br>,
<strong>, etc., which is not possible for a button created with an <input> element.
 Syntax: <button type = “value”>Text Here</button>

5. <select>, <option> and <optgroup> elements


 The <select> element is used to create a drop-down list where users can select one or
more options.
 It acts as the container for <option> elements, which defines the available choices.
 <select> attributes:
o name: The name of the <select> element, used to reference it in form data (when
submitted) and in JavaScript.
o id: Assigns a unique identifier to the <select> element, allowing it to be easily
targeted by CSS and JavaScript.
o multiple: It allows users to select more than one option, without this attribute
only single selection is allowed.
o size: It specifies the number of visible options in the list. If omitted, a dropdown
appears. If set to a larger value, it will display a list box with multiple items
shown.

 The <option> element defines the individual items that the user can choose from within
a <select> meny.
 Each <option> element has a value attribute, which is sent as the value of the form
when the option is selected.
 The text inside the <option> tag is what the user sees in the drop-down list.
 <option> attributes
o value: Specifies value sent to the server when the form is submitted.
o selected: Pre-selects an option when the form is first loaded.
o disabled: Disables the option, making it unselectable by the user.

 The <optgroup> element is used to group related options within a <select> element.
 It is useful when you have a large list of options, and want to categorize them under
different labels, which is provided by the label attribute.
 <optgroup> attributes:
o label: Defines the name if the group, which is displayed to the user to indicate
the grouping.
o disabled: Disables the entire group of options.
<form>
<label for = “food”>Select your favourite food: </label>
<select id = “food” name = “foodItems” multiple size = “5”>
<optgroup label = “Fruits”>
<option value = “Apple” selected>Apple</option>
<option value = “Orange” disabled>Orange (Out of Stock) </option>
</optgroup>
<optgroup label = “Vegetables”>
<option value = “Carrot” >Carrot</option>
<option value = “Spinach” >Spinach</option>
</optgroup>
</select>
</form>

6. The <datalist> element


 The <datalist> element is used to provide a list of pre-definedoptions for an <input>
element.
 It allows users to choose from a set of options while still having the flexibility to enter
a custom value if none of the options in the list are suitable.
 Unlike the <select> element which restricts the user to the provided options, <datalist>
offers suggestions but doesn’t limit the input strictly to the listed values.
<input type = “text” id = “food” name = “food” list = “foodlist”>
<datalist id = “foodlist”>
<option value = “apple”>
<option value = “banana”>
</datalist>
7.<fieldset> and <legend> elements
 The <fieldset> is used to group related elements within a form.
 It visually separates the sections of the form and helps organize it better.
 The <legend> element is used inside the fieldset to provide a caption or title for the
group of form elements.
 It serves as a label for the entire section of the form, giving users context about the
fields grouped within the fieldset.

<fieldset>
<legend>Personal Information</legend>
<label for = “f_name”>First Name</label>
<input type = “text” id = “f_name”>
<label for = “l_name”>Last Name</label>
<input type = “text” id = “l_name”>
</fieldset>
Form Events

Form events are actions or occurrences that happen in a form, which can be handled using JS
to perform actions, like validating inputs, submitting data, or giving feedback to users. When
JS is included in HTML, it reacts over these events and allows execution. This process of
reacting over the events is called event handling, which is done via event handlers.

Mouse Events
Mouse events are triggered when users interact with a form, using the mouse. These events are
common when dealing with clickable elements like button, checkboxes, or even just hovering
over form components.

Common Mouse events:

Event Performed Event Handler Description


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

Key Events
Key events are triggered when the user interacts with a form using the keyboard. They are
useful for handling input validation, submission triggers and providing real-time feedback
when the user is typing.

Common Key Events:

Event Event Description


Performed Handler
Keydown onkeydown When a key is pressed down
Keyup onkeyup When the user releases the key after pressing it
Keypress onkeypress When a key is pressed, but only for character keys. It is similar to
‘onkeydown’, but does not capture non-character keys like Shift, Alt,
or arrow keys.
Input oninput When the input value of an element is changed, either via typing,
pasting or any other input method.
JS Program to demonstrate Mouse Events:
<html>
<head>
<title>Mouse Events </title>
<style>
#mouseArea {
width: 300px;
height: 200px;
border: 2px solid black;
text-align: center;
}
</style>
</head>
<body>
<h1>Mouse Events in JavaScript</h1>
<div id="mouseArea">Interact with this area</div>
<p id="eventLog">Event Log: None</p>
<script>
const mouseArea = document.getElementById('mouseArea');
const eventLog = document.getElementById('eventLog');
function logEvent(event) {
eventLog.textContent = "Event Log: " + event.type;
}
mouseArea.addEventListener('click', logEvent); // Single click
mouseArea.addEventListener('double click', logEvent); // Double click
mouseArea.addEventListener('mousedown', logEvent); // Mouse button pressed
mouseArea.addEventListener('mouseup', logEvent); // Mouse button released
mouseArea.addEventListener('mouseover', logEvent); // Mouse pointer enters the element
mouseArea.addEventListener('mouseout', logEvent); // Mouse pointer leaves the element
mouseArea.addEventListener('mousemove', logEvent); // Mouse pointer moves inside the element
</script>
</body>
</html>
JS Program to demonstrate Key Events:
<!DOCTYPE html>
<html>
<head>
<title>Key Events </title>
<style>
#log {
border: 1px solid #ccc;
width: 300px;
height: 100px;
overflow-y: auto;
}</style>
</head>
<body>
<p>Press any key to see the events in action:</p>
<div id="log"></div>
<script>
function logMessage(message) {
let logDiv = document.getElementById('log');
let newMessage = document.createElement('div');
newMessage.textContent = message;
logDiv.appendChild(newMessage);
logDiv.scrollTop = logDiv.scrollHeight;
}
document.addEventListener('keydown', function(event) {
logMessage(`Keydown event: Key "${event.key}" (code: ${event.code})`);
});
document.addEventListener('keypress', function(event) {
logMessage(`Keypress event: Key "${event.key}" (code: ${event.code})`);
});
document.addEventListener('keyup', function(event) {
logMessage(`Keyup event: Key "${event.key}" (code: ${event.code})`);
});
</script>
</body>
</html>
Other Events:

Event Event Description


Performed Handler
focus onfocus When the user focuses on an element
submit onsubmit When the user submits the form
blur onblur When the focus is away from a form element
change onchange When the user modifies or changes the value of a form element
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the browser unloads it
resize onresize When the visitor resizes the window of the browser

Form Objects and Elements


Browser Object Model (BOM)
The BOM is used to interact with the browser. It acts as a toolkit which gives developers access
to the browser’s environment so that they can make things happen when you visit a website,
such as
 Open or close browser
 Check internet connection
 Show popup alerts
The BOM enables access and manipulation of the browser window, frames and other browser
related objects by facilitating the JS Code.
Window Object
The window object represents a window in the browser. It is the default object of the browser.
Hence, an object of window is created automatically by the browser.
Note: Window is an object of the browser and not of JavaScript. JavaScript objects are string, array, etc.
Window Object Methods:
1. alert() – It displays an alert box containing a message with ‘OK’ button.
2. confirm() – It displays the confirm dialog box containing a message with OK and cancel
buttons.
3. prompt() – It displays a dialog box to get input from user.
4. open() – It opens a new window.
5. close() – It closes the current window.
6. setTimeout() – It performs actions after specified time like calling a function, evaluating
expressions, etc.
Objects defined Under Window Object:
 History Object
 Navigator Object
 Screen Object
 Location Object
 Document Object
1. History Object
The History Object represents the array of URLs visited by the user. By using this object,
previous, forward, or any particular page can be loaded. The history object is in the window
object. So, it can be accessed by
window.history
OR
history
Property of History Object:
1. length – It returns the length of the history URLs.
Methods of the History Object:
1. forward() – Loads the next page. Example: history.forward();//for next page
2. back() – Loads the previous page. Example: history.back();//for previous page
3. go() – Loads the given page number.
Example: history.go(2);//for next 2nd page
history.go(-2);//for previous 2nd page
2. Navigator Object
The JavaScript navigator object is used for browser detection. It can be used to get browser
information such as appName, appCodeName, userAgent etc.
The navigator object is the window property, so it can be accessed by:
window.navigator
OR
navigator
Properties of the Navigator Object:
Sr. Property Description
No.
1 appName returns the name
2 appVersion returns the version
3 appCodeName returns the code name
4 cookieEnabled returns true if cookie is enabled otherwise false
5 userAgent returns the user agent
6 language returns the language. It is supported in Netscape and Firefox only.
7 userLanguage returns the user language. It is supported in IE only.
8 plugins returns the plugins. It is supported in Netscape and Firefox only.
9 systemLanguage returns the system language. It is supported in IE only.
10 mimeTypes[] returns the array of mime type. It is supported in Netscape and Firefox only.
11 platform returns the platform e.g. Win32.
12 online returns true if browser is online otherwise false.
Methods of Navigator object:
Sr. No. Method Description
1 javaEnabled() checks if java is enabled.
2 taintEnabled() checks if taint is enabled. It is deprecated since JavaScript 1.2.

<html>
<body>
<script>
document.writeln("<br/>navigator.appCodeName: "+navigator.appCodeName);
document.writeln("<br/>navigator.appName: "+navigator.appName);
document.writeln("<br/>navigator.appVersion: "+navigator.appVersion);
document.writeln("<br/>navigator.cookieEnabled: "+navigator.cookieEnabled);
document.writeln("<br/>navigator.language: "+navigator.language);
document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);
document.writeln("<br/>navigator.platform: "+navigator.platform);
document.writeln("<br/>navigator.onLine: "+navigator.onLine);
</script>
</body>
</html>

3. Screen Object
It holds information of the browser screen. It can be used to display screen width, height, color
depth, pixel depth, etc. It can be accessed by
window.screen
OR
screen
Properties of the Screen Object:
Sr. Property Description
No.
1 width returns the width of the screen
2 height returns the height of the screen
3 availWidth returns the available width
4 availHeight returns the available height
5 colorDepth returns the color depth
6 pixelDepth returns the pixel depth.
<html>
<body>
<script>
document.writeln("<br/>screen.width: "+screen.width);
document.writeln("<br/>screen.height: "+screen.height);
document.writeln("<br/>screen.availWidth: "+screen.availWidth);
document.writeln("<br/>screen.availHeight: "+screen.availHeight);
document.writeln("<br/>screen.colorDepth: "+screen.colorDepth);
document.writeln("<br/>screen.pixelDepth: "+screen.pixelDepth);
</script>
</body>
</html>

4. Location Object
It is used to access and manipulate the current URL of the browser. It provides information
about the URL of the document and allows you to redirect the browser to a new URL. It can
be accessed using

window.location
OR
location
Properties of the Location Object:
Sr. Property Description
No.
1 href Used to get or set the entire URL of the current webpage.
2 protocol Returns the protocol of the current URL.
3 hostname Returns the domain name or IP address of the URL.
4 port Returns the port number of the url. If not specified, it returns an empty string.
5 pathname Returns the path of the url, which includes everything after the domain name.
6 search Returns the query string, including the ‘?’ symbol.
7 hash Returns the fragment identifier, starting with ‘#’.
8 origin Returns the protocol, domain and port of url.
Methods of the Location Object:
Sr. Method Description
No.
1 assign(url) Loads a new document at the specified url.
2 replace(url) Replaces the current document with a new one. The difference between replace and assign is
that replace does not keep the previous page in history, so you cannot use the back button to
go to the previous page.
3 reload(freload) It reloads the current webpage. If freeload is true, it forces the page to reload from the server,
bypassing the cache.
<html>
<body>
<button onclick="showLocationProperties()">Show Location Properties</button>
<button onclick="reloadPage()">Reload Page</button>
<button onclick="redirectPage()">Redirect to Google</button>
<button onclick="replacePage()">Replace Page with Bing</button>
<button onclick="navigateBack()">Back</button>
<button onclick="navigateForward()">Forward</button>
<div id="locationDetails" style="margin-top: 20px;"></div>
<script>
function showLocationProperties() // Function to display location object properties
{ const details = `
<p><strong>Href (Full URL):</strong> ${window.location.href}</p>
<p><strong>Protocol:</strong> ${window.location.protocol}</p>
<p><strong>Host:</strong> ${window.location.host}</p>
<p><strong>Hostname:</strong> ${window.location.hostname}</p>
<p><strong>Port:</strong> ${window.location.port}</p>
<p><strong>Pathname:</strong> ${window.location.pathname}</p>
<p><strong>Search (Query String):</strong> ${window.location.search}</p>
<p><strong>Hash (Anchor):</strong> ${window.location.hash}</p>
<p><strong>Origin:</strong> ${window.location.origin}</p>
`;
document.getElementById('locationDetails').innerHTML = details; }
function reloadPage() // Function to reload the current page
{ window.location.reload();}
function redirectPage() // Function to redirect the user to a new page
{ window.location.href = "https://www.google.com"; }
function replacePage() // Function to replace the current page with another page
{ window.location.replace("https://www.bing.com"); }
function navigateBack() // Function to navigate back in history
{ window.history.back(); }
function navigateForward() // Function to navigate forward in history
{ window.history.forward(); }
</script>
</body>
</html>
5. Document Object
The document object represents the entire html document that is loaded into the web browser’s
window. When html document is loaded in the browser, it becomes a document object. It is
the root element that represents the html document. It serves as an entry point to access and
manipulate the content of a webpage. It provides properties and methods that allows us to
interact with and modify the document object model (DOM). It can be accessed using

window.document
OR
document
Properties of the document object:
Sr. Property Description
No.
1 url Returns the url of the current document.
2 title Gets or sets the title of the document.
3 body Returns the <body> element of the document.
4 head Returns the <head> element of the document.
5 cookie Returns a collection of all the forms in the document.
6 forms Gets or sets the cookies associated with the document.
7 links Returns all the <a> elements in the documents that have the href attribute.
8 images Returns all the images in the document.

Methods of the Document Object:


Sr. Method Description
No.
1 getElementById(id) Returns an element by its ID.
2 getElementsByClassName(className) Returns a collection of elements with the specified class.
3 getElementsByTagName(tagName) Returns a collection of elements with the specified tag name.
4 querySelector(selector) Returns the first element that matches the specified CSS selector.
5 createElement(tagName) Creates a new HTML element.
6 write(content) Writes directly to the document.
7 writeln(content) Writes the given string on the document with newline character at
the end.
8 innerHTML Allows for directly modifying the HTML content inside an element
(e.g., body).
<html>
<body>
<button onclick="showDocumentProperties()">Show Document Properties</button>
<button onclick="changeTitle()">Change Document Title</button>
<button onclick="createElement()">Create New Element</button>
<button onclick="getElementByIdDemo()">Get Element by ID</button>
<button onclick="getElementsByClassNameDemo()">Get Elements by Class Name</button>
<button onclick="getElementsByTagNameDemo()">Get Elements by Tag Name</button>
<button onclick="querySelectorDemo()">Query Selector Demo</button>
<button onclick="writeToDocument()">Write to Document</button>
<button onclick="modifyBodyContent()">Modify Body Content</button>
<div id="documentDetails" style="margin-top: 20px;"></div>
<script>
// Function to display document object properties
function showDocumentProperties() {
const details = `
<p><strong>Document URL:</strong> ${document.URL}</p>
<p><strong>Document Title:</strong> ${document.title}</p>
<p><strong>Document Last Modified:</strong> ${document.lastModified}</p>
<p><strong>Document Domain:</strong> ${document.domain}</p>
<p><strong>Ready State:</strong> ${document.readyState}</p>
<p><strong>Character Set:</strong> ${document.characterSet}</p>
<p><strong>Document Referrer:</strong> ${document.referrer}</p>
`;
document.getElementById('documentDetails').innerHTML = details;
}
// Function to change the document title
function changeTitle() {
document.title = "New Document Title";
alert("Document title has been changed!");
}
// Function to create a new element and add it to the body
function createElement() {
const newElement = document.createElement("p");
newElement.textContent = "This is a new paragraph element created using createElement().";
document.body.appendChild(newElement);
}
// Function to demonstrate getElementById
function getElementByIdDemo() {
const element = document.getElementById("documentDetails");
element.innerHTML = "<strong>Element fetched by ID:</strong> This content was modified using
getElementById.";
}
// Function to demonstrate getElementsByClassName
function getElementsByClassNameDemo() {
const elements = document.getElementsByClassName("demoClass");
Array.from(elements).forEach((element, index) => {
element.textContent = `Modified element ${index + 1} using getElementsByClassName.`;
});}
// Function to demonstrate getElementsByTagName
function getElementsByTagNameDemo() {
const elements = document.getElementsByTagName("button");
Array.from(elements).forEach((button, index) => {
button.textContent = `Button ${index + 1}`;
});}
// Function to demonstrate querySelector
function querySelectorDemo() {
const element = document.querySelector("h1");
element.style.color = "blue";
element.textContent = "H1 element modified using querySelector."; }
// Function to write to the document
function writeToDocument() {
document.write("<p>This text is written using document.write().</p>");}
// Function to modify the body content directly
function modifyBodyContent() {
document.body.innerHTML += "<p>New content added to the body using
document.body.innerHTML.</p>";
}
</script>
<p class="demoClass">This is an element with class "demoClass".</p>
<p class="demoClass">Another element with class "demoClass".</p>
</body>
</html>
Changing Attribute Value Dynamically

HTML Form elements can be accessed using


1. innerHTML – It is used to modify or retrieve the html content of an element.
Syntax: Retrieve – element.innerHTML
Modify - element.innerHTML = value;
2. innerText - It is used to modify or retrieve the text content of an element.
Syntax: Retrieve – element.innerHTML
Modify - element.innerHTML = value;

Note: The key difference between innerHTML and innerText is that innerHTML returns the text content of the
element, including all the spacing and innerHTML tags. On the other hand, innerText returns just the text contents of
all the elements and all the children, without CSS, hidden spacing and tags, except <script> and <style> elements.

To change the attribute value of an element, we need to access that element in JS either using
ID, class_name or any other way. The attribute can be accessed using .attribute_name, and a
new value can be assigned to it.

Syntax: element.attribute = new_value;

The setAttribute() method is also used to set a new value to am attribute. If the attribute does
not exist, it is created first.

Syntax: element.setAttribute(name, value);


Modifying an existing Attribute:
<html>
<body>
<form name = “f1”>
Email: <input id = “i1” type = “email” value = “” name = “n” change = “myfunction()”>
</form>
</script>
function myfunction()
{
var v = document.getElementById(“i1”).value;
document.forms.f1.n.value = v + “@gmail.com”;
}
</script>
</body>
</html>
Creating a NEW ATTRIBUTE:
<html>
<style>
.demo
{
color : red;
}
</style>
<body>
<h2>Changing attribute value dynamically</h2>
<h3 id = “heading”>Hello!</h3>
<form name = “f1”>
<button onClick = “myfunction()”>Click Here</button>
</form>
</script>
function myfunction()
{
document.getElementById(“heading”).setAttribute(“class”, “demo”);
}
</script>
</body>
</html>

Changing Option List Dynamically


To change the selected option programmatically by the value attribute, all we have to do is
change the value property of the <select> element. The select box will then update itself to
reflect the state of this property.

Evaluating Checkbox Selection


A checkbox has two states:

1) Checked

2) Unchecked.

To get the state of a checkbox, you follow these steps:


 First, select the checkbox using a DOM method such as getElementById() or
querySelector().
 Then, access the checked property of the checkbox element. If its checked property is
true, then the checkbox is checked; otherwise, it is not.
querySelector()-The querySelector() method returns the first child element that matches a specified CSS selector(s)
of an element. To return all the matches, use the querySelectorAll() method instead.
Example:
<label for="accept">
<input type="checkbox" id="accept" name="accept" value="yes">Accept
</label>
In script: document.querySelector('#accept').checked

Program to change option list dynamically:


<html>
<body>
<form name="form1">
<select name="op1" size="3">
<option>Apple</option>
<option>Banana</option>
<option>Orange</option>
</select><br><br>
<input type="radio" id="r1" name="f" value=1 onclick="display(this)" checked="true">Fruits
<input type="radio"id="r2"name="f" value=2 onclick="display(this)">Flowers
<p>You have selected <span id="s" style="color:red">--------</span>.See the change in the above list.</p>
</form>
<script>
function display(e) {
with(document.forms.form1) {
if(e.value==1) {
document.getElementById("s").innerHTML="Fruits";
op1[0].text="Apple"
op1[0].value=1
op1[1].text="Banana"
op1[1].value=2
}
if(e.value==2) {
document.getElementById("s").innerHTML="Flowers";
op1[0].text="Mogra"
op1[0].value=1
op1[1].text="Chafa"
op1[1].value=2
}
}
}
</script>
</body>
</html>

Changing label dynamically

JS allows to use 2 in-built properties to change the text of any element in the html document.
The <label> tag helps in improving the usability of the webpage for mouse users, as it can
toggle the text inside it, if the user clicks on it. This can be done using
 the innerHTML
 the innerText

<html>
<body>
<form>
<label for="fname"id="l1">First name:</label><br>
<input type="text" id="fname" name="fname" onchange="changeLabel(this.value)"><br><br>
<label for="lname"id="l2">Last name:</label><br>
<input type="text" id="lname" name="lname" ><br><br>
<input type="button" value="Submit" >
</form>
<script>
function changeLabel(v)
{
document.getElementById("l2").innerHTML="Last Name of "+v;
}
</script>
</body>
</html>
Manipulating Form Elements

DOM manipulation in JS is an important factor while creating a web application using HTML
and JS. It is the process of interacting with the DOM API to modify an HTML document that
will be displayed in a web browser. This HTML document can be changed to add or remove
elements, update existing elements, rearrange existing elements, etc.

By manipulating the DOM, we can create web applications that update the data in a web page
without refreshing the page and can change its layout as well. Throughout the document, items
can be deleted, moved or rearranged.

<html>
<body>
<form name="form1">
Program Code:<input type="text" name="n"><br><br>
Semester:<input type="number" name="s"><br><br>
Master code:<input type="text" name="m"><br><br>
Course:<input type="text"name="c" onclick="myFunction()"><br><br>
<button type="button" >Submit</button>
</form>
<script>
function myFunction()
{
with(document.forms.form1)
{
if(n.value.length==2&&s.value.length==1&&m.value.length==1)
{
c.value=n.value.toUpperCase()+s.value+m.value.toUpperCase();
c.style.background="yellow";
}
}
}
</script>
</body>
</html>
Intrinsic JS Functions

An intrinsic (or built - in) function is a function available for use in a given programming
language whose implementation is handled specially by the compiler. It is often used to replace
the submit button and the reset button with your own graphical images, which are displayed on
a form in place of these buttons.

<html>
<head>
<title>Using Intrinsic JavaScript Functions</title>
</head>
<body>
<h2>Intrinsic Javascript Function</h2>
<form name="contact" onsubmit="sub(); return false;" onreset="res()">
First Name: <INPUT type="text" name="Fname"/> <BR><BR>
Last Name: <INPUT type="text" name="Lname"/><BR><BR>
Email: <INPUT type="text" name="Email"/><BR><BR>
<img src="submit.jpg" height="60" width="80" onclick="document.forms.contact.submit()"/>
<img src="reset.jpg" height="60" width="80" onclick="document.forms.contact.reset()"/>
<p id="p1">Form action displayed here</p>
</form>
<script>
function sub() {
document.getElementById("p1").innerHTML = "Form Submitted";
}
function res() {
document.getElementById("p1").innerHTML = "Form is cleared";
}
</script>
</body>
</html>
Disabling Element

The ‘disabled’ is a Boolean attribute. When present, it specifies that element should be
disabled. A disabled element is usable. The disabled attribute can be set to keep the user from
using an element until some other condition has been met. Then, some JS code could remove
the disabled value, and make the element usable again.
Syntax: element.disabled = true;

Read-Only Elements

The ‘readOnly’ property checks whether a text-field is read-only or not. The default value for
this attribute is false. A read-only field cannot be modified. However, a user can tab to it,
highlight it, and copy text from it.
Syntax: retrieve – textObject.readOnly;
modify – textObject.readOnly = true/false;

<html>
<body>
<form>
<input type="text" value = "Disabled and read-only elements." readOnly = true size = 50><br><br>
Temporary Address: <input type="text" id="temp-address" name="temp-address" required><br><br>
Permanent Address: <input type="text" id="perm-address" name="perm-address" required><br><br>
<label> Are both the addresses same?</label>
<input type="radio" id="yes" name="same-address" value="yes" onclick="toggleAddress(true)">Yes
<input type="radio" id="no" name="same-address" value="no" onclick="toggleAddress(false)" checked>No
</form>
<script>
function toggleAddress(isSame) {
const permAddress = document.getElementById('perm-address');
if (isSame) {
permAddress.value = document.getElementById('temp-address').value;
permAddress.disabled = true;
} else {
permAddress.disabled= false;
permAddress.value = ''; // Clear the value when 'No' is selected
}}
</script>
</body>
</html>

You might also like