CSS Unit 3
CSS Unit 3
Forms .................................................................................................................................... 2
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">
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!
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).
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>
<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.
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.
<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.
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.
The setAttribute() method is also used to set a new value to am attribute. If the attribute does
not exist, it is created first.
1) Checked
2) Unchecked.
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>