Name of the School: School of Computer Science and
Engineering
Course Code: E2UC304C Course Name:Java & Java Script
DEPARTMENT OF COMPUTER SCIENCE
& ENGINEERING
Subject Name: Java Programming
Day: 13
Topics Covered: Form Creation & Validation
1
Faculty Name: Dr. Avinash Dwivedi Programe Name: B.Tech (CSE,AI &ML)
Prerequisites, Objectives and Outcomes
Prerequisite of topic: Basic concepts related to programming
Objective: To make students to apply JavaScript in web programming.
Outcome : 1. Student will be able to know to use different ways to add
JavaScript in HTML.
2. Students will be able to apply DOM model in developing web pages.
3. Students will be able to implement in practical applications.
2
Javascript
JavaScript was developed by Brendan Eich in 1995,
which appeared in Netscape, a popular browser of that
time.
JavaScript is a programming language for use in
HTML pages
Invented in 1995 at Netscape Corporation
(LiveScript)
JavaScript has nothing to do with Java
JavaScript programs are run by an interpreter built
into the user's web browser (not on the server)
Javascript in web designing
1. client opens connection to server
2. client sends request to server
3. server sends response to client
4. client and server close connection
What about Step 5?
5. Client renders (displays) the response received
from server
• Step 5 involves displaying HTML
And running any JavaScript code within the HTML
What can JavaScript Do?
JavaScript can dynamically modify an HTML page
JavaScript can react to user input
JavaScript can validate user input
JavaScript can be used to create cookies (yum!)
JavaScript is a full-featured programming language
JavaScript user interaction does not require any
communication with the server
Pros and Cons of JavaScript
Pros:
– Allows more dynamic HTML pages, even complete web
applications
Cons:
– Requires a JavaScript-enabled browser
– Requires a client who trusts the server enough to run the
code the server provides
JavaScript has some protection in place but can still cause security
problems for clients
– Remember JavaScript was invented in 1995 and web
browsers have changed a lot since then
A script or scripting language is a computer language with a
series of commands within a file that is capable of being
executed without being compiled.
All scripting languages are programming languages.
The theoretical difference between the language and script
language is that scripting languages do not require the
compilation step and are rather interpreted.
For example, normally, a C program needs to be compiled
before running whereas normally, a scripting language like
JavaScript or PHP need not be compiled.
Some popular facts about JavaScript.
Javascript is the only client side programming language for web browser.
JavaScript can build interactivity Websites.
Javascript is Object Based with prototype inheritance model for OOPS.
Javascript is Case Sensitive.
Javascript can put dynamic content into a webpage. .
Javascript can react to events like Mouse Click, mouse hover, mouse out, form
submit etc known as JavaScript Events.
Javascript can validate form data.
Javascript can detect user's browser and operating system using navigator Object.
Javascript can be used to create cookies.
Javascript can add cool animation to a webpage JS timing functions.
Javascript can detect user physical location using HTML5 Geolocation API.
Some popular facts about JavaScript.
Javascript can also be used to draw shapes, graphs, create animations and games
development using HTML5 Canvas.
At present, Javascript has lot of libraries and framework, exp JQuery, Angular JS,
React JS, Backbone JS etc, thus making Javascript more popular.
Javascript can also be used in developing server side application using Node JS.
Popular Editors like, VS Code, Atom and Brackets are written in Javascript (Electron
Framework of Node JS).
Advantages of scripts
Open source, allowing users to view and edit
the script if needed.
Does not require the file to be compiled, but may be
when necessary.
Easy to learn and write.
Easy to port between different operating systems.
Much faster to develop than an actual program - some
individuals and companies write scripts as a prototype
for actual programs.
JavaScript is an open source & most popular client side
scripting language supported by all browsers.
JavaScript is used mainly for enhancing the interaction of a
user with the webpage
Hello World
<!DOCTYPE HTML>
<html>
<body>
<p>Before the script...</p>
<script> alert( 'Hello, world!' );
</script>
<p>...After the script.</p>
</body>
</html>
How do JavaScript engines work?
JavaScript Engines are complicated. But it works on some simple
basics:
The engine reads ("parses:) the script.
Then it converts or compiles the script to the machine language.
After that machine code runs.
Here, JavaScript engine applies optimizations at each step of the
process. It reads a compiled script and analyzes the data that
passes in JavaScript engine. After that, it applies optimizations to
the machine code from that acquired knowledge. When this process
is completed, scripts run quite fast.
Javascript advantages
Show dynamic content based on the user profile.
React to user's operations, like mouse clicks events, key presses
or pointer movements.
Support features like auto-validated form entries and interactive
drop-down menus.
Send requests to remote servers, Upload and download files.
JavaScript code can also create movement and sound
Ask questions to the users, Get and set cookies, show
messages, switch browser tabs.
Allows the data on to be stored in the local storage.
Javascript limitations are
JavaScript on a webpage may not allow you to copy, execute or read/write
arbitrary files on the hard disk.
It doesn't offer any access to Operating system functions.
Many browsers allow it to work with files, but the access is very limited and
only provided if the user is performing a specific action like, dropping a file
into a browser window or selecting using <input> tag.
JavaScript allows you to communicate over the net to the server where the
current page came from. Although, it does not allow you to receive data from
other sites/domains.
Three most important features of JS
Here, are the three most important features which
make JavaScript unique
It offers full integration with HTML/CSS.
Simple things are done quickly without any complication or
following strict rules.
Supported by all major browsers and JavaScript is enabled by
default.
JS : Client Side Script
JavaScript is a very powerful client-side scripting language.
JavaScript is used mainly for enhancing the interaction of a user
with the webpage. In other words, you can make your webpage
more lively and interactive, with the help of JavaScript.
JavaScript is also being used widely in game development
and Mobile application development.
Different ways to add JS
1. In head tag
2. In body tag
3. External java script inclusion
4. Through HTML tag like innerHTML
JS in Head / Body tags
You can have any number of scripts
Scripts can be placed in the HEAD or in the BODY
– In the HEAD, scripts run before the page is
displayed
– In the BODY, scripts run as the page is displayed
In the HEAD is the right place to define functions
and variables that are used by scripts within the
BODY
Using JavaScript in head tag
<html>
<head>
<title>Hello World in JavaScript</title>
<script type="text/javascript">
function helloWorld() {
document.write("Hello World!");
}
</script>
</head>
<body>
<script type= "text/javascript">
helloWorld();
</script>
</body>
</html>
Using JavaScript in body tag
<!DOCTYPE html>
<html><head><title>JavaScript prompt() method</title>
</head>
<body style = "text-align: center;">
<h1 style = "color: red;">Hello World</h1>
<script>
var num1 = parseInt(window.prompt("Enter the first number"));
var num2 = parseInt(window.prompt("Enter the second number "));
document.write(num1+num2);
</script>
</body></html>
External Scripts
Scripts can also be loaded from an external file
This is useful if you have a complicated script or set of
subroutines that are used in several different documents
<script src= "myscript.js"></script>
External JS
<html>
<head>
<script type="text/javascript" src=“abc.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick=“show()"/>
</form>
</body>
// In the file abc.js
</html> function show(){
alert("Hello Students");
}
JS with innerHTML
<HTML>
<HEAD> <script type="text/javascript">
function changeText2(){
var userInput = document.getElementById('userInput').value;
document.getElementById('pdata').innerHTML = userInput;
}
</script></HEAD>
<BODY>
<p>Welcome to the site <b id='pdata'>India</b> </p>
<input type='text' id='userInput' value='Enter Text Here' />
<input type='button' onclick='changeText2()' value='Change Text'/>
</BODY>
</HTML>
Demo
Program to add numbers using Text Boxes
<!doctype html> <body>
<p>Enter the First Number: <input id="first"></p>
<html> <p>Enter the Second Number: <input id="second"></p>
<button onclick="add()">Add</button>
<head>
<p>Sum = <input id="answer"></p>
<script>
</body>
</html>
function add()
{
var numOne, numTwo, sum;
numOne = parseInt(document.getElementById("first").value);
numTwo = parseInt(document.getElementById("second").value);
sum = numOne + numTwo;
document.getElementById("answer").value = sum;
}
</script></head>
Stop
Blank submission
<html> <head><script language="javascript">
function check(){
var x = document.getElementById('comment_box').value
if (x == null || x == "") {
document.getElementById('comment_error').innerHTML = "*The box cant be left blank!";
return false
}
}
</script>
<body>
<form action="", name="", method="">
<p style="color: red;" id="comment_error"></p>
<textarea rows="3" id="comment_box" name=""></textarea>
<input type="submit" name="commit" value="Post Comment"
onclick="return check()">
</form> </body></html>
Email Validation
<html>
<head><script language="javascript">
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
</script></head>
<body>
<form name="myform" method="post" action="#" onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>
</body></html>
JavaScript Variables
JavaScript has variables that you can declare with
the optional var keyword
Variables declared within a function are local to
that function
Variables declared outside of any function are
global variables
var myname = “Raju dhar"
JavaScript Operators and Constructs
• JavaScript has most of the operators we're used to
from C/Java
– Arithmetic (+, - ,* , /, %)
– Assignment (=, += , -= , *= /= , %= , ++, --)
– Logical (&&, ||, !)
– Comparison (<, >, <= , >= , ==. ===)
• Note: + also does string concatentation
• Constructs:
– if, else, while, for, switch, case
Simple User Interaction
• There are three built-in methods of doing simple
user interaction
– alert(msg) alerts the user that something has happened
– confirm(msg) asks the user to confirm (or cancel)
something
– prompt(msg, default) asks the user to enter some text
alert(“Beware of Dogs");
confirm("Are you sure you want to do that?");
prompt("Enter you name”, "Adil");
JavaScript Functions
JavaScript lets you define functions using the
function keyword
Functions can return values using the return
keyword
function showConfirm() {
confirm("Are you sure you want to do that?");
}
JavaScript Arrays
• JavaScript has arrays that are indexed starting at 0
• Special version of for works with arrays
<script type="text/javascript">
var colors = new Array();
colors[0] ="red"; colors[1] ="green";
colors[2] ="blue"; colors[3] ="orange";
colors[4] ="magenta"; colors[5] ="cyan";
for (var i in colors) {
document.write("<div style=\"background-color:“ + colors[i] +
";\">“ + colors[i] + "</div>\n");
}
</script>
Java Script to fetch data from Text box
<form><br>
Enter your First Name: <input type="text" id="firstname"/><br><br>
Enter your Last Name: <input type="text" id="lastname"/><br><br>
<input type="submit" value="Submit" onclick="formdata()"/><br>
</form>
<script>
function formdata()
{
var firstname1= document.getElementById("firstname").value;
var lastname1= document.getElementById("lastname").value;
document.writeln("<h1>Confirmation Page</h1><br>");
document.writeln("Thank you for completing this form.<br><br>");
document.writeln("The first name you entered is " + firstname + "<br>");
document.writeln("The last name you entered is " + lastname);
}
</script>
Value from Radio Button
<!--Check selected Radio Button value using JavaScript.-->
<html><head> <title>Check selected Radio Button value using JavaScript.</title>
<script type="text/javascript">
function checkGender(){
if(document.getElementById('radioMale').checked)
alert("You have selected Male.");
else
alert("You have selected Female.");
}
</script> </head>
<body style="text-align: center;">
<h1>Check selected Radio Button value using JavaScript.</h1>
<b>Choose gender: </b><br><br>
<input type="radio" id="radioMale" value="Male">Male</input>
<input type="radio" id="radioFemale" value="Female">Female</input> <br>
<input type="button" value="Check Gender" onClick="checkGender()"/>
</body> </html>
Value from Check Box
<!DOCTYPE html><html lang="en">
<body>
<input type="checkbox" name="laptop" value="HP">HP laptop<br>
<input type="checkbox" name="laptop" value="DELL">DELL laptop<br>
<input type="checkbox" name="laptop" value="MAC">MAC laptop<br>
<input type="checkbox" name="laptop" value="ASUS">ASUS laptop<br>
<input type=“button” value= “Get Value onClick="getValue()">
<script>
function getValue() {
let checkboxes = document.getElementsByName('laptop');
let result = "";
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
result += checkboxes[i].value + " " + " Laptop, ";
}
}
document.write("<p> You have selected : " + result + "</p>"); }
</script> </body> </html>
Value from Drop Down
<!DOCTYPE html> <html> <body>
<form>
Select your favorite fruit:
<select id="mySelect">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pineapple">Pineapple</option>
<option value="banana">Banana</option>
</select>
</form>
<p>Click the button to return the value of the selected fruit.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p id="demo"></p> <script>
function myFunction() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = x;
}
</script> </body></html> </html>
JavaScript Object
Object is a non-primitive data type in JavaScript. It is like any other variable,
the only difference is that an object holds multiple values in terms of
properties and methods.
Properties can hold values of primitive data types and methods are
functions.
JavaScript, an object can be created in two ways:
Object literal
Object constructor
Object Literal
The object literal is a simple way of creating an object using { }
brackets. You can include key-value pair in { }, where key would
be property or method name and value will be value of property
of any data type or a function. Use comma (,) to separate
multiple key-value pairs.
var <object-name> = { key1: value1, key2: value2,... keyN:
valueN};
Example: Create Object using Object Literal Syntax
var emptyObject = {}; // object with no properties or methods
var person = { firstName: "John" }; // object with single property
// object with single method
var message = { showMessage: function (val) {
alert(val);
}
};
// object with properties & method
var person = { firstName: "James", lastName: "Bond", age: 15,
getFullName: function () {
return this.firstName + ' ' + this.lastName
}
};
Access JavaScript Object Properties & Methods
var person = {
firstName: "James", lastName: "Bond", age: 25,
getFullName: function () {
return this.firstName + ' ' + this.lastName
}
};
person.firstName; // returns James
person.lastName; // returns Bond
person["firstName"];// returns James
person["lastName"];// returns Bond
person.getFullName();
Object Constructor
var person = new Object();
// Attach properties and methods to person object
person.firstName = "James";
person["lastName"] = "Bond";
person.age = 25;
person.getFullName = function () {
return this.firstName + ' ' + this.lastName;
};
// access properties & methods
person.firstName; // James
person.lastName; // Bond
person.getFullName(); // James Bond
Pop up boxes
JavaScript dialog box are of following three types:
JavaScript dialog box for getting confirmation on any user
input
JavaScript dialog box for raising an alert box
JavaScript dialog box for a kind of input from the user
Alert Box
<!DOCTYPE HTML>
<html>
<head>
<title>JavaScript alert Box</title>
</head>
<body>
<h3>JavaScript alert Box Example</h3>
<script type="text/javascript">
alert("Welcome to JIMS! This is an alert box.");
</script>
</body>
</html>
Confirm Box
<!DOCTYPE html>
<html><body>
<h2>JavaScript Confirm Box</h2>
<input type= “button” value= “Confirm Demo” onClick="myFunction()">
<p id="demo"></p>
<script>
function myFunction() {
var txt;
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
Prompt Box
A prompt box is often used if you want the user to input a value
before entering a page.
When a prompt box pops up, the user will have to click either
"OK" or "Cancel" to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user
clicks "Cancel" the box returns null.
Syntax
window.prompt("sometext","defaultText");
Program: Prompt Box
<!DOCTYPE html>
<html><head><title>JavaScript prompt() method</title>
<script>
function fun() {
var a = prompt("Enter some text", “Deafaul value GU");
if (a != null) {
document.getElementById("para").innerHTML = "Welcome to " + a;
}
}
</script>
</head>
<body style = "text-align: center;">
<h1 style = "color: red;">Hello World</h1><h2>
<button onclick = "fun()">Click me</button>
<p id = "para"></p>
</body></html>
Adding 2 Numbers using Prompt Box
<!DOCTYPE html>
<html><head><title>JavaScript prompt() method</title>
<script>
function fun() {
var num1 = parseInt(window.prompt("Enter the first number"));
var num2 = parseInt(window.prompt("Enter the second number "));
alert(num1+num2)
}
</script>
</head>
<body style = "text-align: center;">
<h1 style = "color: red;">Hello World</h1>
<button onclick = "fun()">Click me</button>
</body></html>
window object
The window object represents a window in browser. An object of window is
created automatically by the browser.
Window is the object of browser, it is not the object of javascript. The
javascript objects are string, array, date etc.
Methods of Window object
Method Description
alert() displays the alert box containing message with ok button.
confirm() displays the confirm dialog box containing message with ok and
cancel button.
prompt() displays a dialog box to get input from the user.
open() opens the new window.
close() closes the current window.
setTimeout() performs action after specified time like calling function, evaluating
expressions etc.
Method Description
alert() displays an alert box with a message and an OK button
blur() removes the focus from the current window
clearInterval() clears the timer, which is set by using the setInterval() method
clearTimeout() clears the timer, which is set by using the setTimeout() method
close() closes the current window
confirm() displays a dialog box with a message and two buttons, OK and Cancel
createPopup() creates a pop-up window
focus() sets focus on the current window
moveBy() moves a window relative to its current position
moveTo() moves a window to an specified position
open() opens a new browser window
Window Methods
sends a print command to print the content of the current
print()
window
prompt() prompts for input
resizeBy() resizes a window with the specified pixels
resizeTo() resizes a window with the specified width and height
scrolls the content of a window by the specified number of
scrollBy()
pixels
scrolls the content of a window up to the specified
scrollTo()
coordinates
evaluates an expression at specified time intervals in
setInterval()
milliseconds
evaluates an expression after a specified number of
setTimeout()
milliseconds
JavaScript History Object
The JavaScript history object represents an array of URLs visited by the user. By
using this object, you can load previous, forward or any particular page.
The history object is the window property, so it can be accessed by:
window.history
Property of JavaScript history object
There are only 1 property of history object.
No. Property Description
1 length returns the length of the history URLs.
Methods of JavaScript history object
There are only 3 methods of history object.
No. Method Description
1 forward() loads the next page.
2 back() loads the previous page.
3 go() loads the given page number.
Example
history.back();//for previous page
history.forward();//for next page
history.go(2);//for next 2nd page
history.go(-2);//for previous 2nd page
Math object
Method Description
abs(x) gives the absolute value of x
acos(x) gives arccosine of x (in radian)
asin(x) gives arcsine of x (in radian)
atan(x) gives the arctangent of x
gives the arctangent of the quotient on dividing y
atan2(y,x)
and x
ceil(x) rounds up x to the nearest bigger integer
cos(x) gives cosine value of x
exp(x) gives the value of ex
floor(x) rounds up x to the nearest smaller integer
log(x) gives the natural logarithmic value of x
max(x,y,z,...,n) gives the highest number from the given list
min(x,y,z,...,n gives the lowest number from the given list
pow(x,y) returns x to the power of y
random() returns a random number between 0 and 1
round(x) rounds up x to the nearest integer
sin(x) gives the sine value of x
sqrt(x) gives the square root of x
tan(x) gives the tangent value of x
JavaScript 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
Property of JavaScript navigator object
No. Property Description
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.
<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>
navigator.appCodeName: Mozilla
navigator.appName: Netscape
navigator.appVersion: 5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
navigator.cookieEnabled: true
navigator.language: en-US
navigator.userAgent: Mozilla/5.0 (Windows NT 6.2; WOW64)
AppleWebKit/537.36
(KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
navigator.platform: Win32
navigator.onLine: true
Arrays
There are two syntaxes for creating an empty array:
let arr = new Array();
let arr = [];
We can supply initial elements in the brackets:
let fruits = ["Apple", "Orange", "Plum"];
Array elements are numbered, starting with zero.
We can get an element by its number in square brackets:
let fruits = ["Apple", "Orange", "Plum"];
alert( fruits[0] ); // Apple
alert( fruits[1] ); // Orange
alert( fruits[2] ); // Plum
We can replace an element:
fruits[2] = 'Pear'; // now ["Apple", "Orange", "Pear"]
…Or add a new one to the array:
fruits[3] = 'Lemon'; // now ["Apple", "Orange", "Pear",
"Lemon"]
The total count of the elements in the array is
its length:
let fruits = ["Apple", "Orange", "Plum"];
alert( fruits.length ); // 3
JavaScript Events
• JavaScript can be made to respond to user events
• Common Events:
– onload and onunload : when a page is first visited or
left
– onfocus, onblur, onchange : events pertaining to
form
elements
– onsubmit : when a form is submitted
– onmouseover, onmouseout : for "menu effects"
Exception Handling
• JavaScript also has try, catch, and throw
keywords for handling JavaScript errors
try {
runSomeCode();
} catch(err) {
var txt= "There was an error on this page.\n\n"
+ "Error description: “ + err.description + "\n\n"
alert(txt)
}
Comments in JavaScript
• Comments in JavaScript are delimited with // and /*
*/ as in Java and C++
JavaScript Objects
• JavaScript is object-oriented and uses the same
method-calling syntax as Java
• We have already seen this with the document
object
document.write("Hello World!");
Built-In JavaScript Objects
• Some basic objects are built-in to JavaScript
– String
– Date
– Array
– Boolean
– Math
JavaScript Strings
A String object is created every time you use a
string literal (just like in Java)
• Have many of the same methods as in Java
– charAt, concat, indexOf, lastIndexOf, match, replace, search,
slice, split, substr, substring, toLowerCase, toUpperCase,
valueOf
• There are also some HTML specific methods
– big, blink, bold, fixed, fontcolor, fontsize, italics, link, small,
strike, sub, sup
• Don't use the HTML methods (use CSS instead)
– This is the worst kind of visual formatting
JavaScript Dates
• The Date class makes working with dates easier
• A new date is initialized with the current date
• Dates can be compared and incremented
var myDate = new Date();
myDate.setFullYear(2007,2,14);
var today = new Date();
var nextWeek = today + 7;
if (nextWeek > today) {
alert("You have less than one week left");
}
The JavaScript Math Class
• The Math class encapsulates many commonlyused
mathematical entities and formulas
• These are all class methods
– abs, acos, asin, atan, atan2, ceil, cos, exp, floor, log, max,
min, pow, random, round, sin, sqrt, tan
• These are all class methods
– E, LN2, LN10, LOG2E, LOG10E, PI, SQRT1_2, SQRT2
if (Math.cos(Math.PI) != 0) {
alert("Something is wrong with Math.cos");
}
JavaScript and the DOM
• The Document Object Model (DOM) is a
specification that determines a mapping between
programming language objects and the elements
of an HTML document
• Not specific to JavaScript
HTML DOM Objects
• Environment objects
– Window, Navigator, Screen, History, Location, Document
• HTML objects
– Anchor, Area, Base, Body, Button, Event, Form, Frame,
Frameset, Iframe, Image, Checkbox, FileUpload, Hidden,
Password, Radio, Reset, Submit, Text, Link, Meta, Object,
Option, Select, Style, Table, TableCell, TableRow, TextArea
HTML DOM: Document
• The Document object represents an HTML
document and can be used to access all
documents in a page
• A Document contains several collections
– anchors, forms, images, links
• Has several properties
– body, cookie, domain, lastModified, referrer, title, URL
• Has several useful methods
– getElementById, getElementsByName,
getElementsByTagName, write, writeln, open, close
• An instance of Document is already created for you, called document
function changeF() {
var cText = document.getElementById("c");
var fText = document.getElementById("f");
...
}
…<input type= "text" id= "c" onchange=
"changeC()">C
<input type=
"text" id=
"f" onchange=
"changeF()">F
HTML DOM: Form Elements
• One of the most common uses of JavaScript is for
form validation
• Several HTML DOM classes encapsulate form
elements
– Form, Button, Checkbox, Hidden, Password, Text,
Radio,
Reset, Submit, Textarea
• Warning: Using JavaScript is not a substitute for
validating form data in CGI scripts
HTML DOM: Text
• A text entry field (input type=
"text") is
encapsulated by a Text object
• Variables
– value, maxLength, id, size, name, tabindex, readOnly
• Changing these variables has an immediate effect
on the displayed data
HTML DOM: The Document Tree
• Accessing elements and changing their properties
lets us do simple things like form validation, data
transfer etc
• HTML DOM lets us do much more
• We can create, delete, and modify parts of the
HTML document
• For this we need to understand the Document Tree
Navigating the Document Tree
HTML DOM: The Document Tree
References:
https://www.geeksforgeeks.org/
https://www.javatpoint.com/exception-handling-in-java
https://www.tutorialspoint.com/java/java_exceptions.htm
The complete reference, eleventh edition, available at:
https://gfgc.kar.nic.in/sirmv-science/GenericDocHandler/1
38-a2973dc6-c024-4d81-be6d-5c3344f232ce.pdf
79
Thank you
80