Unit-5 Java Script Minors
Unit-5 Java Script Minors
As mentioned before, Javascript is one of the most widely used programming languages (Front-end
as well as Back-end). It has it's presence in almost every area of software development. I'm going to list
few of them here:
● Client side validation - This is really important to verify any user input before submitting it to
the server and Javascript plays an important role in validting those inputs at front-end itself.
● Manipulating HTML Pages - Javascript helps in manipulating HTML page on the fly. This
helps in adding and deleting any HTML tag very easily using javascript and modify your HTML
to change its look and feel based on different devices and requirements.
● User Notifications - You can use Javascript to raise dynamic pop-ups on the webpages to give
different types of notifications to your website visitors.
● Back-end Data Loading - Javascript provides Ajax library which helps in loading back-end data
while you are doing some other processing. This really gives an amazing experience to your
website visitors.
● Presentations - JavaScript also provides the facility of creating presentations which gives
website look and feel. JavaScript provides RevealJS and BespokeJS libraries to build a web-
based slide presentations
1
Advantages of JavaScript
● Less server interaction − You can validate user input before sending the
page to the server. This saves server traffic, which means less load
on your server.
● Immediate feedback to the visitors − They don't have to wait for a page reload
to see if they have forgotten to enter something.
● Increased interactivity − You can create interfaces that react when the
user hovers over them with a mouse or activates them via the
keyboard.
● Richer interfaces − You can use JavaScript to include such items as drag-
and-drop components and sliders to give a Rich Interface to your
site visitors.
Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script should be included in or
referenced by an HTML document for the code to be interpreted by the browser.
It means that a web page need not be a static HTML, but can include programs that interact with the
user, control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI server-side
scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail address in
a form field.
The JavaScript code is executed when the user submits the form, and only if all the entries are valid,
they would be submitted to the Web Server.
JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is
normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these tags as a
script. A simple syntax of your JavaScript will appear as follows.
2
<script ...>
JavaScript code
</script>
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.
You can use spaces, tabs, and newlines freely in your program and you are free to format and indent
your programs in a neat and consistent way that makes the code easy to read and understand.
JavaScript Datatypes
One of the most fundamental characteristics of a programming language is the set of data types it
supports. These are the type of values that can be represented and manipulated in a programming
language.
3
JavaScript Variables
Like many other programming languages, JavaScript has variables. Variables can be thought of as
named containers. You can place data into these containers and then refer to the data simply by naming
the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the
var keyword as follows.
You can also declare multiple variables with the same var keyword as follows −
JavaScript uses the keywords var, let and const to declare variables.
● You should not use any of the JavaScript reserved keywords as a variable name. These keywords
are mentioned in the next section. For example, break or boolean variable names are not valid.
● JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or
an underscore character. For example, 123test is an invalid variable name but _123test is a valid
one.
● JavaScript variable names are case-sensitive. For example, Name and name are two different
variables.
4
In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
Example:
let x;
x = 6;
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Variables</h2>
<p id="demo"></p>
<script>
let x;
x = 6;
document.write( x);
</script>
</body>
</html>
5
JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type.
Unlike many other languages, you don't have to tell JavaScript during variable declaration what type of
value the variable will hold. The value type of a variable can change during the execution of a program
and JavaScript takes care of it automatically.
6
do import static with
double in super
● Arithmetic Operators
● Comparison Operators
● Logical (or Relational) Operators
● Assignment Operators
● Conditional (or ternary) Operators
Arithmetic Operators
JavaScript supports the following arithmetic operators −
1 + (Addition)
2 - (Subtraction)
3 * (Multiplication)
7
4 / (Division)
5 % (Modulus)
6 ++ (Increment)
7 -- (Decrement)
Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" +
10 will give "a10".
Example
<html>
<body>
<script type="text/javascript">
<!--
var a = 33;
var b = 10;
8
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);
a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);
b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->
9
</script>
OUTPUT
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
++a = 35
--b = 8
Comparison Operators
JavaScript supports the following comparison operators −
1 = = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition
becomes true.
2 != (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal,
then the condition becomes true.
Ex: (A != B) is true.
10
3 > (Greater than)
Checks if the value of the left operand is greater than the value of the right operand,
if yes, then the condition becomes true.
Checks if the value of the left operand is less than the value of the right operand, if
yes, then the condition becomes true.
Checks if the value of the left operand is greater than or equal to the value of the
right operand, if yes, then the condition becomes true.
Checks if the value of the left operand is less than or equal to the value of the right
operand, if yes, then the condition becomes true.
Logical Operators
JavaScript supports the following logical operators −
11
1 && (Logical AND)
If both the operands are non-zero, then the condition becomes true.
2 || (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
3 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical NOT
operator will make it false.
Example:
<html>
<body>
<script type="text/javascript">
<!--
var a = 95;
var b = false;
var linebreak = "<br />";
12
document.write("!(a && b) => ");
result = (!(a && b));
document.write(result);
document.write(linebreak);
//-->
</script>
OUTPUT:
(a && b) => false
(a || b) => true
!(a && b) => true
Bitwise Operators
Ex: (A & B) is 2.
2 | (BitWise OR)
Ex: (A | B) is 3.
13
3 ^ (Bitwise XOR)
Ex: (A ^ B) is 1.
4 ~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand.
It moves all the bits in its first operand to the left by the number of places specified
in the second operand. New bits are filled with zeros. Shifting a value left by one
position is equivalent to multiplying it by 2, shifting two positions is equivalent to
multiplying by 4, and so on.
Ex: (A << 1) is 4.
Binary Right Shift Operator. The left operand’s value is moved right by the number
of bits specified by the right operand.
Ex: (A >> 1) is 1.
This operator is just like the >> operator, except that the bits shifted in on the left
are always zero.
Ex: (A >>> 1) is 1.
14
Example:
<html>
<body>
<script type="text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";
15
</script>
OUTPUT:
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 8
(a >> b) => 4
Assignment Operators
= (Simple Assignment )
1
Assigns values from the right side operand to the left side operand
Ex: C += A is equivalent to C = C + A
Ex: C -= A is equivalent to C = C - A
16
*= (Multiply and Assignment)
4
It multiplies the right operand with the left operand and assigns the result to the left
operand.
Ex: C *= A is equivalent to C = C * A
Ex: C /= A is equivalent to C = C / A
Ex: C %= A is equivalent to C = C % A
Miscellaneous Operator
We will discuss two operators here that are quite useful in JavaScript: the conditional operator (? :) and
the typeof operator.
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then executes one of
the two given statements depending upon the result of the evaluation.
? : (Conditional )
1
If Condition is true? Then value X : Otherwise value Y
Example code:
<html>
17
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
</body>
</html>
OUTPUT:
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
18
typeof Operator
The typeof operator is a unary operator that is placed before its single operand, which can be of any
type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or
boolean value and returns true or false based on the evaluation.
Number "number"
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
<html>
<body>
19
result = (typeof a == "string" ? "A is String" : "A is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
//-->
</script>
The var keyword is used in all JavaScript code from 1995 to 2015.
If you want your code to run in older browser, you must use var.
If you think the value of the variable can change, use let.
Example:
<!DOCTYPE html>
<html>
<body>
20
<h1>JavaScript Variables</h1>
<p id="demo"></p>
<script>
price1 = 5;
const price2 = 6;
price1=price1+1
let total = price1 + price2;
document.getElementById("demo").innerHTML =
"The total is: " + price1;
</script>
</body>
</html>
OUTPUT
Result => B is String
Result => A is Numeric
JavaScript Variables
In this example, price1, price2, and total are variables.
21
Start the statement with let and separate the variables by comma:
Example
let person = "John Doe", carName = "Volvo", price = 200;
Function Definition
Before we use a function, we need to define it. The most common way
to define a function in JavaScript is by using the function keyword,
followed by a unique function name, a list of parameters (that might
be empty), and a statement block surrounded by curly braces.
Syntax
22
Example
Try the following example. It defines a function called sayHello that takes
no parameters −
Calling a Function
To invoke a function somewhere later in the script, you would simply
need to write the name of that function as shown in the following
code.
Live Demo
<html>
<head>
<script type = "text/javascript">
function sayHello() {
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say
Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>
23
OUTPUT:
Hello there!
HTML Events
An HTML event can be something the browser does, or something a user does.
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
In the following example, an onclick attribute (with code), is added to a <button> element:
<!DOCTYPE html>
<html>
<body>
24
<button onclick="document.getElementById('demo').innerHTML=Date()">The time is?</button>
<p id="demo"></p>
</body>
</html>
In the next example, the code changes the content of its own element (using
this.innerHTML):
<!DOCTYPE html>
25
<html>
<body>
</body>
</html>
OUTPUT:
Event Description
26
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
Many different methods can be used to let JavaScript work with events:
String Length
To find the length of a string, use the built-in length property:
<!DOCTYPE html>
<html>
27
<body>
<p id="demo"></p>
<script>
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.getElementById("demo").innerHTML = text.length;
</script>
</body>
</html>
OUTPUT
JavaScript String Properties
The length property returns the length of a string:
26
Event Description
onmouseout The user moves the mouse away from an HTML element
28
onkeydown The user pushes a keyboard key
JavaScript Events
The change in the state of an object is known as an Event. In html, there are various events which
represents that some activity is performed by the user or by the browser. When javascript code is
included in HTML, js react over these events and allow the execution. This process of reacting over the
events is called Event Handling. Thus, js handles the HTML events via Event Handlers.
For example, when a user clicks over the browser, add js code, which will execute the task to be
performed on the event.
Mouse events:
Event Performed Event Handler Description
mouseover onmouseover When the cursor of the mouse comes over the
element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
29
mousemove onmousemove When the mouse movement takes place.
Keyboard events:
Event Performed Event Handler Description
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
Form events:
Event Performed Event Handler Description
change onchange When the user modifies or changes the value of a form
element
Window/Document events
Event Performed Event Handler Description
load onload When the browser finishes the loading of the page
30
unload onunload When the visitor leaves the current webpage, the
browser unloads it
resize onresize When the visitor resizes the window of the browser
31
Example of Focus Event
1. <html>
2. <head> Javascript Events</head>
3. <body>
4. <h2> Enter something here</h2>
5. <input type="text" id="input1" onfocus="focusevent()"/>
6. <script>
7. <!--
8. function focusevent()
9. {
10. document.getElementById("input1").style.background=" aqua";
11. }
12. //-->
13. </script>
14. </body>
15. </html>
Test it Now
32
OUTPUT:
Keydown Event
Example
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
alert("Pressed a key");
}
//-->
</script>
</body>
</html>
33
OUTPUT
Load event
1. <html>
2. <head>Javascript Events
3.
a. <script>
b. <!--
c. document.write("The page is loaded successfully");
d. //-->
e. </script>
4.
5. </head>
6. </br>
7. <body onload="window.alert('Page successfully loaded');">
8.
9. </body>
10. </html>
Output:
34
onfocusin Event
EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<p>When the input field gets focus, a function is triggered which changes the background-color.</p>
<script>
function myFunction(x) {
x.style.background = "yellow";
35
</script>
</body>
</html>
Output:
onfocusout Event
Definition and Usage
The onfocusout event occurs when an element is about to lose focus.
Tip: The onfocusout event is similar to the onblur event. The main difference is that the onblur event
does not bubble. Therefore, if you want to find out whether an element or its child loses focus, you
should use the onfocusout event.
example:
<!DOCTYPE html>
<html>
<body>
<p>When you leave the input field, a function is triggered which transforms the input text to upper
case.</p>
36
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>
OUTPUT:
https://www.w3schools.com/jsref/dom_obj_event.asp
37
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For example: car,
pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is template based not class based. Here, we don't create class to get the object. But, we direct
create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
1. object={property1:value1,property2:value2.....propertyN:valueN}
1. <script>
2. emp={id:102,name:"Shyam Kumar",salary:40000}
3. document.write(emp.id+" "+emp.name+" "+emp.salary);
4. </script>
OUTPUT:
102 Shyam Kumar 40000
38
2) By creating instance of Object
The syntax of creating object directly is given below:
1. <script>
2. var emp=new Object();
3. emp.id=101;
4. emp.name="Ravi Malik";
5. emp.salary=50000;
6. document.write(emp.id+" "+emp.name+" "+emp.salary);
7. </script>
1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6. }
7. e=new emp(103,"Vimal Jaiswal",30000);
8.
9. document.write(e.id+" "+e.name+" "+e.salary);
10. </script>
39
Output of the above example
103 Vimal Jaiswal 30000
1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6.
7. this.changeSalary=changeSalary;
8. function changeSalary(otherSalary){
9. this.salary=otherSalary;
10. }
11. }
12. e=new emp(103,"Sonoo Jaiswal",30000);
13. document.write(e.id+" "+e.name+" "+e.salary);
14. e.changeSalary(45000);
15. document.write("<br>"+e.id+" "+e.name+" "+e.salary);
16. </script>
Let's see the simple example of creating and using array in JavaScript.
1. <script>
2. var emp=["Sonoo","Vimal","Ratan"];
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br/>");
5. }
6. </script>
40
Test it Now
Sonoo
Vimal
Ratan
1. <script>
2. var i;
3. var emp = new Array();
4. emp[0] = "Arun";
5. emp[1] = "Varun";
6. emp[2] = "John";
7.
8. for (i=0;i<emp.length;i++){
9. document.write(emp[i] + "<br>");
10. }
11. </script>
Test it Now
Arun
Varun
John
41
Here, you need to create instance of array by passing arguments in constructor so that we don't have to
provide value explicitly.
1. <script>
2. var emp=new Array("Jai","Vijay","Smith");
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br>");
5. }
6. </script>
Test it Now
Jai
Vijay
Smith
Methods Description
concat() It returns a new array object that contains two or more merged arrays.
copywithin() It copies the part of the given array with its own elements and returns the
modified array.
entries() It creates an iterator object and a loop that iterates over each key/value pair.
every() It determines whether all the elements of an array are satisfying the provided
function conditions.
42
1. <script>
2. var str="This is string literal";
3. document.write(str);
4. </script>
Test it Now
Output:
1. <script>
2. var stringname=new String("hello javascript string");
3. document.write(stringname);
4. </script>
Test it Now
Output:
43
Methods Description
indexOf() It provides the position of a char value present in the given string.
lastIndexOf() It provides the position of a char value present in the given string
by searching a character from the last position.
substr() It is used to fetch the part of the given string on the basis of the
specified starting position and length.
substring() It is used to fetch the part of the given string on the basis of the
specified index.
slice() It is used to fetch the part of the given string. It allows us to assign
positive as well negative index.
44
toLowerCase() It converts the given string into lowercase letter.
toLocaleLowerCase() It converts the given string into lowercase letter on the basis of
host?s current locale.
toLocaleUpperCase() It converts the given string into uppercase letter on the basis of
host?s current locale.
split() It splits a string into substring array, then returns that newly
created array.
trim() It trims the white space from the left and right side of the string.
1. <script>
2. var str="javascript";
3. document.write(str.charAt(2));
4. </script>
Test it Now
Output:
45
2) JavaScript String concat(str) Method
The JavaScript String concat(str) method concatenates or joins two strings.
1. <script>
2. var s1="javascript ";
3. var s2="concat example";
4. var s3=s1.concat(s2);
5. document.write(s3);
6. </script>
Test it Now
Output:
1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.indexOf("from");
4. document.write(n);
5. </script>
Test it Now
Output:
11
1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.lastIndexOf("java");
46
4. document.write(n);
5. </script>
Test it Now
Output:
16
1. <script>
2. var s1="JavaScript toLowerCase Example";
3. var s2=s1.toLowerCase();
4. document.write(s2);
5. </script>
Test it Now
Output:
1. <script>
2. var s1="JavaScript toUpperCase Example";
3. var s2=s1.toUpperCase();
4. document.write(s2);
5. </script>
Test it Now
Output:
47
7) JavaScript String slice(beginIndex, endIndex) Method
The JavaScript String slice(beginIndex, endIndex) method returns the parts of string from given
beginIndex to endIndex. In slice() method, beginIndex is inclusive and endIndex is exclusive.
1. <script>
2. var s1="abcdefgh";
3. var s2=s1.slice(2,5);
4. document.write(s2);
5. </script>
Test it Now
Output:
cde
1. <script>
2. var s1=" javascript trim ";
3. var s2=s1.trim();
4. document.write(s2);
5. </script>
Test it Now
Output:
javascript trim
1. <script>
2. var str="This is JavaTpoint website";
3. document.write(str.split(" ")); //splits the given string.
4. </script>
48
OUTPUT:
This,is,JavaTpoint,website
What is this?
In JavaScript, the this keyword refers to an object.
Methods like call(), apply(), and bind() can refer this to any object.
EXAMPLE
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
49
<script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
</body>
</html>
output
John Doe
JavaScript Math
50
The JavaScript math object provides several constants and methods to perform mathematical operation.
Unlike date object, it doesn't have constructors.
Methods Description
ceil() It returns a smallest integer value, greater than or equal to the given number.
floor() It returns largest integer value, lower than or equal to the given number.
51
max() It returns maximum value of the given numbers.
Math.sqrt(n)
The JavaScript math.sqrt(n) method returns the square root of the given number.
Test it Now
52
Output:
Math.random()
The JavaScript math.random() method returns the random number between 0 to 1.
Test it Now
Output:
Math.pow(m,n)
The JavaScript math.pow(m,n) method returns the m to the power of n that is mn.
Test it Now
Output:
Math.floor(n)
The JavaScript math.floor(n) method returns the lowest integer for the given number. For example 3 for
3.7, 5 for 5.9 etc.
53
4. </script>
Test it Now
Output:
Math.ceil(n)
The JavaScript math.ceil(n) method returns the largest integer for the given number. For example 4 for
3.7, 6 for 5.9 etc.
Test it Now
Output:
Math.round(n)
The JavaScript math.round(n) method returns the rounded integer nearest for the given number. If
fractional part is equal or greater than 0.5, it goes to upper value 1 otherwise lower value 0. For
example 4 for 3.7, 3 for 3.3, 6 for 5.9 etc.
Test it Now
Output:
54
Math.abs(n)
The JavaScript math.abs(n) method returns the absolute value for the given number. For example 4 for -
4, 6.6 for -6.6 etc.
Test it Now
Output:
By the help of Number() constructor, you can create number object in JavaScript. For example:
If value can't be converted to number, it returns NaN(Not a Number) that can be checked by isNaN()
method.
Test it Now
Output:
55
JavaScript Number Constants
Let's see the list of JavaScript number constants with description.
Constant Description
Methods Description
toExponential() It returns the string that represents exponential notation of the given
number.
56
toFixed() It returns the string that represents a number with exact digits after a
decimal point.
JavaScript Boolean
JavaScript Boolean is an object that represents value in two states: true or false. You can create the
JavaScript Boolean object by Boolean() constructor as given below.
constructor returns the reference of Boolean function that created Boolean object.
57
Method Description
The Browser Object Model (BOM) is used to interact with the browser.
The default object of browser is window means you can call all the functions of window by specifying
window or directly. For example:
window.alert("hello javatpoint");
is same as:
alert("hello javatpoint");
You can use a lot of properties (other objects) defined underneath the window object like document,
history, screen, navigator, location, innerHeight, innerWidth,
Note: The document object represents an html document. It forms DOM (Document Object Model).
Window Object
58
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.
Note: if html document contains frame or iframe, browser creates additional window objects for each
frame.
Method Description
alert()
confirm() displays the confirm dialog box containing message with ok and cancel
button.
setTimeout() performs action after specified time like calling function, evaluating
expressions etc.
1. <script type="text/javascript">
2. function msg(){
59
3. alert("Hello Alert Box");
4. }
5. </script>
6. <input type="button" value="click" onclick="msg()"/>
It displays the confirm dialog box. It has message with ok and cancel buttons.
1. <script type="text/javascript">
2. function msg(){
3. var v= confirm("Are u sure?");
4. if(v==true){
5. alert("ok");
6. }
7. else{
8. alert("cancel");
9. }
10.
11. }
12. </script>
13.
14. <input type="button" value="delete record" onclick="msg()"/>
60
It displays prompt dialog box for input. It has message and textfield.
1. <script type="text/javascript">
2. function msg(){
3. var v= prompt("Who are you?");
4. alert("I am "+v);
5.
6. }
7. </script>
8.
9. <input type="button" value="click" onclick="msg()"/>
1. <script type="text/javascript">
2. function msg(){
3. open("http://www.javatpoint.com");
4. }
5. </script>
6. <input type="button" value="javatpoint" onclick="msg()"/>
61
1. <script type="text/javascript">
2. function msg(){
3. setTimeout(
4. function(){
5. alert("Welcome to Javatpoint after 2 seconds")
6. },2000);
7.
8. }
9. </script>
10.
11. <input type="button" value="click" onclick="msg()"/>
1. window.history
Or,
1. history
62
No. Property Description
63
You can use different Date constructors to create date object. It provides methods to get and set day,
month, year, hour, minute and seconds.
Constructor
You can use 4 variant of Date constructor to create date object.
1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)
Methods Description
getDate() It returns the integer value between 1 and 31 that represents the
day for the specified date on the basis of local time.
getDay() It returns the integer value between 0 and 6 that represents the
day of the week on the basis of local time.
getFullYears() It returns the integer value that represents the year on the basis of
local time.
getHours() It returns the integer value between 0 and 23 that represents the
hours on the basis of local time.
getMilliseconds() It returns the integer value between 0 and 999 that represents the
milliseconds on the basis of local time.
64
getMinutes() It returns the integer value between 0 and 59 that represents the
minutes on the basis of local time.
getMonth() It returns the integer value between 0 and 11 that represents the
month on the basis of local time.
getSeconds() It returns the integer value between 0 and 60 that represents the
seconds on the basis of local time.
getUTCDate() It returns the integer value between 1 and 31 that represents the
day for the specified date on the basis of universal time.
getUTCDay() It returns the integer value between 0 and 6 that represents the
day of the week on the basis of universal time.
getUTCFullYears() It returns the integer value that represents the year on the basis of
universal time.
getUTCHours() It returns the integer value between 0 and 23 that represents the
hours on the basis of universal time.
getUTCMinutes() It returns the integer value between 0 and 59 that represents the
minutes on the basis of universal time.
getUTCMonth() It returns the integer value between 0 and 11 that represents the
month on the basis of universal time.
getUTCSeconds() It returns the integer value between 0 and 60 that represents the
seconds on the basis of universal time.
setDate() It sets the day value for the specified date on the basis of local
time.
65
setDay() It sets the particular day of the week on the basis of local time.
setFullYears() It sets the year value for the specified date on the basis of local
time.
setHours() It sets the hour value for the specified date on the basis of local
time.
setMilliseconds() It sets the millisecond value for the specified date on the basis of
local time.
setMinutes() It sets the minute value for the specified date on the basis of local
time.
setMonth() It sets the month value for the specified date on the basis of local
time.
setSeconds() It sets the second value for the specified date on the basis of local
time.
setUTCDate() It sets the day value for the specified date on the basis of
universal time.
setUTCDay() It sets the particular day of the week on the basis of universal
time.
setUTCFullYears() It sets the year value for the specified date on the basis of
universal time.
setUTCHours() It sets the hour value for the specified date on the basis of
universal time.
setUTCMilliseconds() It sets the millisecond value for the specified date on the basis of
universal time.
66
setUTCMinutes() It sets the minute value for the specified date on the basis of
universal time.
setUTCMonth() It sets the month value for the specified date on the basis of
universal time.
setUTCSeconds() It sets the second value for the specified date on the basis of
universal time.
toUTCString() It converts the specified date in the form of string using UTC time
zone.
Let's see the simple example to print date object. It prints date and time both.
Test it Now
67
Output:
Current Date and Time: Wed Jul 06 2022 09:53:41 GMT+0000 (Coordinated Universal Time)
1. <script>
2. var date=new Date();
3. var day=date.getDate();
4. var month=date.getMonth()+1;
5. var year=date.getFullYear();
6. document.write("<br>Date is: "+day+"/"+month+"/"+year);
7. </script>
Output:
Test it Now
Output:
68
JavaScript Digital Clock Example
Let's see the simple example to display digital clock using JavaScript date object.
There are two ways to set interval in JavaScript: by setTimeout() or setInterval() method.
Test it Now
Output:
69
What is the Document Object Model?
1. The Document Object Model (DOM) is a programming
API for HTML and XML documents. It defines the logical
structure of documents and the way a document is
accessed and manipulated
2. With the Document Object Model, programmers can
create and build documents, navigate their structure,
and add, modify, or delete elements and content.
3. Anything found in an HTML or XML document can be
accessed, changed, deleted, or added using the
Document Object Model.
70
<TD>Shady Grove</TD>
<TD>Aeolian</TD>
</TR>
<TR>
<TD>Over the River, Charlie</TD>
<TD>Dorian</TD>
</TR>
</ROWS>
</TABLE>
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
71
● JavaScript can create new HTML events in the page
In other words: The HTML DOM is a standard for how to get, change, add, or delete
HTML elements.
When html document is loaded in the browser, it becomes a document object. It is the root
element that represents the html document. It has properties and methods. By the help of
document object, we can add dynamic content to our web page.
1. window.document
Is same as
72
1. document
According to W3C - "The W3C Document Object Model (DOM) is a platform and language-neutral
interface that allows programs and scripts to dynamically access and update the content,
structure, and style of a document."
73
The important methods of document object are as follows:
Method Description
writeln("string") writes the given string on the doucment with newline character
at the end.
getElementsByName() returns all the elements having the given name value.
getElementsByTagName() returns all the elements having the given tag name.
getElementsByClassName() returns all the elements having the given class name.
Property Description
74
element.innerHTML = new html content Change the inner HTML of an element
Method Description
Here, document is the root element that represents the html document.
75
value is the property, that returns the value of the input text.
Let's see the simple example of document object that prints name with welcome message.
1. <script type="text/javascript">
2. function printvalue(){
3. var name=document.form1.name.value;
4. alert("Welcome: "+name);
5. }
6. </script>
7.
8. <form name="form1">
9. Enter Name:<input type="text" name="name"/>
10. <input type="button" onclick="printvalue()" value="print name"/>
11. </form>
76
In the previous page, we have used document.form1.name.value to get the value of the input
value. Instead of this, we can use document.getElementById() method to get value of the input
text. But we need to define id for the input field.
Let's see the simple example of document.getElementById() method that prints cube of the given
number.
1. <script type="text/javascript">
2. function getcube(){
3. var number=document.getElementById("number").value;
4. alert(number*number*number);
5. }
6. </script>
7. <form>
8. Enter No:<input type="text" id="number" name="number"/><br/>
9. <input type="button" value="cube" onclick="getcube()"/>
10. </form>
77
Javascript - document.getElementsByName()
method
1. getElementsByName() method
2. Example of getElementsByName()
1. document.getElementsByName("name")
In this example, we going to count total number of genders. Here, we are using
getElementsByName() method to get all the genders.
78
1. <script type="text/javascript">
2. function totalelements()
3. {
4. var allgenders=document.getElementsByName("gender");
5. alert("Total Genders:"+allgenders.length);
6. }
7. </script>
8. <form>
9. Male:<input type="radio" name="gender" value="male">
10. Female:<input type="radio" name="gender" value="female">
11.
12. <input type="button" onclick="totalelements()" value="Total Genders">
13. </form>
79
Javascript - innerHTML
1. javascript innerHTML
2. Example of innerHTML property
The innerHTML property can be used to write the dynamic html on the html document.
It is used mostly in the web pages to generate the dynamic html such as registration form,
comment form, links etc.
document.getElementById('mylocation').innerHTML=data;
}
</script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()">
<div id="mylocation"></div>
</form>
</body>
</html>
80
Show/Hide Comment Form Example using innerHTML
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>First JS</title>
5. <script>
6. var flag=true;
7. function commentform(){
8. var cform="<form action='Comment'>Enter Name:<br><input type='text'
name='name'/><br/>
9. Enter Email:<br><input type='email' name='email'/><br>Enter Comment:<br/>
10. <textarea rows='5' cols='70'></textarea><br><input type='submit' value='Post
Comment'/></form>";
11. if(flag){
12. document.getElementById("mylocation").innerHTML=cform;
13. flag=false;
14. }else{
15. document.getElementById("mylocation").innerHTML="";
16. flag=true;
17. }
18. }
19. </script>
20. </head>
21. <body>
22. <button onclick="commentform()">Comment</button>
23. <div id="mylocation"></div>
24. </body>
25. </html>
81
Javascript - innerText
1. javascript innerText
2. Example of innerText property
The innerText property can be used to write the dynamic text on the html document. Here, text
will not be interpreted as html text but a normal text.
It is used mostly in the web pages to generate the dynamic content such as writing the validation
message, password strength etc.
82
Javascript innerText Example
In this example, we are going to display the password strength when releases the key after press.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" >
function validate() {
var msg;
if(document.myForm.userPass.value.length>5){
msg="good";
}
else{
msg="poor";
}
document.getElementById('mylocation').innerText=msg;
}
</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()">
Strength:<span id="mylocation">no strength</span>
</form>
</body>
</html>
83
1. JavaScript form validation
2. Example of JavaScript validation
3. JavaScript email validation
It is important to validate the form submitted by the user because it can have inappropriate
values. So, validation is must to authenticate user.
JavaScript provides facility to validate the form on the client-side so data processing will be
faster than server-side validation. Most of the web developers prefer JavaScript form validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers and more
fields.
54.9M
1.2K
Here, we are validating the form on form submit. The user will not be forwarded to the next page
until given values are correct.
<html>
<body>
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
84
}
</script>
<body>
<form name="myform" method="post"
action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return validateform()"
>
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
if(firstpassword==secondpassword){
return true;
85
}
else{
alert("password must be same!");
return false;
}
}
</script>
</head>
<body>
</body>
</html>
OUTPUT:
86