Java Script
Java Script
JavaScript - Overview
JS stands for JavaScript. It is a text-based, lightweight, cross-platform, and
interpreted scripting programming language. This language is very popular for
developing web pages. It can be used both on the client-side and server-side.
What is JS in HTML?
JavaScript is the Programming Language for the Web. JavaScript can update
and change both HTML and CSS.
Summary:
Advantages of JavaScript
The merits of using JavaScript are −
● Less server interaction − You can validate user input before sending the
page off 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.
Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the
following important features −
● Client-side JavaScript does not allow the reading or writing of files. This
has been kept for security reason.
● JavaScript cannot be used for networking applications because there is no
such support available.
● JavaScript doesn't have any multi-threading or multiprocessor capabilities.
Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
● Client-side validation,
● Dynamic drop-down menus,
● Displaying date and time,
● Displaying pop-up windows and dialog boxes (like an alert dialog box,
confirm dialog box and prompt dialog box),
● Displaying clocks etc.
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
3
What is JavaScript ?
JavaScript is a dynamic computer programming language. It is lightweight and
most commonly used as a part of web pages, whose implementations allow
client-side script to interact with the user and make dynamic pages. It is an
interpreted programming language with object-oriented capabilities.
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
4
JavaScript - Syntax
● 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.
<script ...>
JavaScript code
</script>
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
5
● Language − This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML
(and XHTML, its successor) have phased out the use of this attribute.
● Type − This attribute is what is now recommended to indicate the scripting
language in use and its value should be set to "text/javascript".
Example:−
<html>
<body>
<h2>Welcome to JavaScript</h2>
<script language = "javascript" type = "text/javascript">
document.write("Hello JavaScript by JavaScript");
</script>
</body>
</html>
Example:
<html>
<body>
<script type="text/javascript">
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
6
Output:
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
7
In this example, we are creating a function msg(). To create function in JavaScript, you
need to write function with function_name as given below.
To call function, you need to work on event. Here we are using onclick event to call
msg() function.
<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello Javatpoint");
}
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
8
It provides code re-usability because a single JavaScript file can be used in several html
pages.
Let's create an external JavaScript file that prints Hello Javatpoint in an alert dialog box.
message.js
function msg(){
alert("Hello Javatpoint");
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
9
Let's include the JavaScript file into the html page. It calls the JavaScript function on
button click.
index.html
<html>
<head>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
</form>
</body>
</html>
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
10
JavaScript Introduction
JavaScript Comments
The JavaScript comments are a meaningful way to deliver messages. It is used to add
information about the code, warnings or suggestions so that end users can easily
interpret the code.
The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the
browser.
1. To make code easy to understand It can be used to elaborate the code so that
end users can easily understand the code.
2. To avoid the unnecessary code It can also be used to avoid the code being
executed. Sometimes, we add the code to perform some action. But after
sometime, there may be a need to disable the code. In such case, it is better to
use comments.
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
11
JavaScript variable
A JavaScript variable is simply the name of a storage location.
There are two types of variables in JavaScript : local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
Example:
1. var x = 10;
2. var _value="sonoo";
What is the purpose of the let, const, and var keywords in JavaScript, and
how do they differ?
The `let`, `const`, and `var` keywords are used for variable declaration in
JavaScript, but they have some differences in terms of scope, reassignment, and
hoisting:
1. var:
→ Variables declared with `var` are function-scoped, meaning they are
accessible within the function in which they are declared.
→ `var` variables can be reassigned and re-declared within the same scope
without generating an error.
→ `var` variables are hoisted to the top of their function scope, meaning they
are available throughout the entire function regardless of where they are
declared.
Example:
function example() {
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
12
var x = 10;
if (true) {
var x = 20; // This reassigns the outer 'x'
console.log(x); // Outputs: 20
}
console.log(x); // Outputs: 20
}
2. `let`:
→ Variables declared with `let` are block-scoped, meaning they are only
accessible within the block (e.g., within loops, conditionals, or function bodies) in
which they are declared.
→ `let` variables can be reassigned, but attempting to redeclare them in the
same scope will result in an error.
→ `let` variables are not hoisted to the top of their block scope, so they are not
accessible before the declaration statement.
Example:
function example() {
let x = 10;
if (true) {
let x = 20; // This creates a new 'x' within the block
console.log(x); // Outputs: 20
}
console.log(x); // Outputs: 10
}
3.`const`:
→ Variables declared with `const` are also block-scoped.
→ `const` variables must be assigned a value when they are declared, and
once assigned, their value cannot be changed (i.e., they are immutable).
→ Attempting to reassign a `const` variable will result in an error, but the value
of a `const` variable that holds an object or array can still be modified.
Example:
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
13
function example() {
const x = 10;
x = 20; // This will cause an error
}
JavaScript is a dynamic type language, that is we don't need to specify the type of the
variable because it is dynamically used by the JavaScript engine. You need to use var
here to specify the data type. It can hold any type of values such as numbers, strings
etc. For example:
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
14
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands.
1. Arithmetic Operators
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
15
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
/ Division 20/10 = 2
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
16
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
17
= Assign 10+10 = 20
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
18
Operator Description
like if-else.
single statement.
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
19
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript
action to be performed.
Keyword Description
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
20
Control statements
1. If Statement
2. If else statement
3. if else if statement
JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if
statement is given below.
Syntax:
if(expression){
//content to be evaluated
Example:
<html>
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
21
<body>
<script>
var a=20;
if(a>10)
{
document.write("value of a is greater than 10");
}
</script>
</body>
</html>
Syntax:
if(expression){
else{
Example:
<html>
<body>
<script>
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
22
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
</body>
</html>
Syntax:
if(expression1){
else if(expression2){
else if(expression3){
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
23
else{
Example:
<html>
<body>
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
24
</body>
</html>
JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple expressions.
But it is convenient than if..else..if because it can be used with numbers, characters etc.
Syntax:
switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......
default:
Example:
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
25
<!DOCTYPE html>
<html>
<body>
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
</body>
</html>
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
26
JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or
for-in loops. It makes the code compact. It is mostly used in array.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
Example:
<!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
27
}
</script>
</body>
</html>
while (condition)
code to be executed
Example:
<!DOCTYPE html>
<html>
<body>
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
28
</body>
</html>
do{
code to be executed
}while (condition);
Example:
<!DOCTYPE html>
<html>
<body>
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
</body>
</html>
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
29
Syntax
for (key in object) {
Example:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const person = {fname:"John", lname:"Doe", age:25};
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
30
JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.
Syntax:
Function Invocation
The code inside the function will execute when "something" invokes (calls) the
function:
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
31
1.Example
<html>
<body>
<script>
function msg(){
alert("Function called when an event occur");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
</body>
</html>
2.Example
<!DOCTYPE html>
<html>
<body>
<script>
</script>
</body>
</html>
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
32
3. Example:
<html>
<body>
<script>
//self invoking function
(function(){
alert("Auto Invoked Function");
})();
</script>
</body>
</html>
Example:
<script>
function getcube(number)
{
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
33
Example:
<!Doctype html>
<html>
<body>
<script>
function add()
{
Var x=10,y=20;
return x+y;
}
var sum=add();
</script>
<script>
document.write(“addition=” + sum);
</script>
</body>
</html>
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
34
Syntax
new Function ([arg1[, arg2[, ....argn]],] functionBody)
Example:
<script>
document.writeln(add(2,5));
</script>
Method Description
apply() It is used to call a function containing this value and a single array of
arguments.
call() It is used to call a function containing this value and an argument list.
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
35
JavaScript Array
JavaScript array is an object that represents a collection of similar types of elements.
1. By array literal
var arrayname=[value1,value2.....valueN];
Example:
<html>
<body>
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
</body>
</html>
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
36
Example:
<html>
<body>
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>
Example:
<html>
<body>
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
37
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>
Methods Description
concat() It returns a new array object that contains two or more merged
arrays.
Syntax:
array.concat(arr1,arr2,....,arrn)
Example:
<script>
var arr1=["C","C++","Python"];
var arr2=["Java","JavaScript","Android"];
var result=arr1.concat(arr2);
document.writeln(result);
</script>
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
38
copywithin() It copies the part of the given array with its own elements and
Syntax:
<script>
var
arr=["AngularJS","Node.js","JQuery","Bootstrap"]
// place at 0th position, the element between 1st and 2nd position.
var result=arr.copyWithin(0,1,2);
document.writeln(result);
</script>
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
flatMap() It maps all array elements via mapping function, then flattens the
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
39
from() It creates a new array carrying the exact copy of another array
element.
filter() It returns the new array containing the elements that pass the
find() It returns the value of the first element in the given array that
findIndex() It returns the index value of the first element in the given array that
forEach() It invokes the provided function once for each element of an array.
includes() It checks whether the given array contains the specified element.
indexOf() It searches the specified element in the given array and returns the
keys() It creates an iterator object that contains only the keys of the array,
lastIndexOf() It searches the specified element in the given array and returns the
map() It calls the specified function for every array element and returns the
new array
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
40
reduce(functio It executes a provided function for each value from left to right and
reduceRight() It executes a provided function for each value from right to left and
some() It determines if any element of the array passes the test of the
implemented function.
slice() It returns a new array containing the copy of the part of the given
array.
()
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
41
toString() It converts the elements of a specified array into string form, without
unshift() It adds one or more elements in the beginning of the given array.
values() It creates a new iterator object carrying values for each index in the
array.
JavaScript String
The JavaScript string is an object that represents a sequence of characters.
1. By string literal
2. By string object (using new keyword)
1) By string literal
Example:
<!DOCTYPE html>
<html>
<body>
<script>
var str="This is string literal";
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
42
document.write(str);
</script>
</body>
</html>
The syntax of creating string object using new keyword is given below:
Example:
<!DOCTYPE html>
<html>
<body>
<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>
</body>
</html>
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
43
Methods Description
specified index.
string.
substr() It is used to fetch the part of the given string on the basis
substring() It is used to fetch the part of the given string on the basis
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
44
trim() It trims the white space from the left and right side of the
string.
Console.log():
`console.log()` is a function used in JavaScript to output data to the console,
typically in a web browser's developer tools console or in a Node.js environment.
It is commonly used for debugging purposes or for providing feedback to
developers about the state of their code.
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
45
1.console: This is the global object in JavaScript that provides access to the
browser's debugging console. It has various methods for logging different types
of information.
For example, you can use `console.log()` to print a message to the console:
console.log("Hello, world!");
Additionally, `console.log()` can log objects, arrays, and other complex data
structures, providing a detailed representation of their contents.
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
46
For example:
For example:
var str = 'The quick brown fox jumps over the lazy dog';
var pattern = /fox/;
For example:
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
47
var str = 'The quick brown Fox jumps over the lazy Dog';
var pattern = /fox/i; // Case-insensitive match
4. Common Patterns:
Regular expressions can match common patterns such as character classes
(`[a-z]`, `\d`, `\w`), quantifiers (`+`, `*`, `{n}`, `{n,m}`), anchors (`^`, `$`), and
groups (`()`).
For example:
Example:
<script>
// Test strings
const testStrings = ["apple5", "banana12", "3orange"];
for(i=0;i<testStrings.length;i++)
{
if (regex.test(testStrings[i]))
{
console.log(testStrings[i]," matches the pattern.");
}
else
{
console.log(testStrings[i]," does not match the
pattern.");
}
}
</script>
Output (@Console):
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
49
In this example:
For example:
<script>
var str = 'The quick brown fox jumps over the lazy dog';
var pattern = /fox/;
</script>
In this program, the regular expression `/fox/` is used to search for the pattern
"fox" within the string `str`. The `test()` method returns `true` indicating that the
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
50
pattern exists in the string, and the `match()` method returns an array containing
the matched substring "fox".
JavaScript Objects
Objects creation:
In JavaScript, objects can be created using different methods, including object
literals, constructor functions, the Object.create() method, and ES6
classes. Let's explore each method:
// Object literal
let person = {
name: 'John',
age: 30,
city: 'New York'
};
//object literal using const with an object literal.
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
salary: 25000
};
Note:
1. It is a common practice to declare objects with the const keyword.
2. The object is declared using let, which means its reference can be
reassigned to a different object later in the code.
3. The object is declared using const, which means its reference cannot
be reassigned to a different object after initialization. However, the
properties of the object can still be modified.
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
51
// Constructor function
function Person(name, age, city) {
this.name = name;
this.age = age;
this.city = city;
}
3. Object.create() Method: The Object.create() method creates a new object with the
specified prototype object and properties.
// Prototype object
let personPrototype = {
greet: function() {
return 'Hello, my name is ' + this.name;
}
};
4. ES6 Classes: With the introduction of ES6, JavaScript supports class syntax for
defining objects and their behavior.
// ES6 class
class Person {
constructor(name, age, city) {
this.name = name;
this.age = age;
this.city = city;
}
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
52
greet() {
return 'Hello, my name is ' + this.name;
}
}
Object Modification:
Objects in JavaScript are mutable, which means you can modify their
properties and methods after creation.
Additionally, you can also use methods like Object.assign() and object spread
syntax (...) to modify objects by merging properties from multiple sources.
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
53
this Keyword
In JavaScript, the this keyword refers to an object.
● Methods like call(), apply(), and bind() can refer this to any
object.
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
54
obj.method();
function strictFunction() {
console.log(this === undefined); // true
}
strictFunction();
5. Methods like `call()`, `apply()`, and `bind()`: These methods can explicitly set
`this` to refer to any object.
function greet() {
console.log(`Hello, ${this.name}`);
}
const person = { name: 'Alice' };
greet.call(person); // 'Hello, Alice'
Note: this is not a variable. It is a keyword. You cannot change the value of
this.
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
55
getElementById():
`getElementById()` is a method in JavaScript used to retrieve an HTML element
from the document by its unique identifier (ID). Here's an explanation of how it
works:
Syntax:
document.getElementById(elementId)
→ Return Value: The method returns a reference to the first element in the
document with the specified ID. If no element with the specified ID exists, `null` is
returned.
Example:
<!DOCTYPE html>
<html>
<head>
<title>getElementById Example</title>
</head>
<body>
<div id="exampleDiv">This is a div element with ID "exampleDiv".</div>
<script>
// Retrieving the element with ID "exampleDiv"
var element = document.getElementById("exampleDiv");
In this example:
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
56
The `getElementById()` method is used to retrieve the `<div>` element with the
ID "exampleDiv".
The retrieved element is then modified using the `innerHTML` property to change
its content.
innerHTML:
innerHTML is a property commonly used in web development when working
with HTML elements through JavaScript. It represents the HTML content within
an element. When you access or modify the innerHTML property of a DOM
(Document Object Model) element, you are essentially accessing or modifying
the HTML markup inside that element.
In this code snippet, the HTML content inside the element with the ID
"exampleElement" is replaced with the new HTML markup specified
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
57
There are several ways to take input from the user on a web page. Here are two
common methods:
<form>
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>
<input type="submit" value="Submit">
</form>
When the form is submitted, the data entered by the user is sent to the server for
processing.
2. JavaScript Prompts:
● JavaScript provides a built-in prompt() function that displays a dialog box with a
message to the user, prompting them to input data.
● Example:
The value entered by the user is stored in the variable userInput and can be used in the
JavaScript code.
Note: JavaScript prompts are synchronous and block the execution of further JavaScript
until the user responds.
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
58
It is important to validate the form submitted by the user because it can have
inappropriate values. So, validation is a must to authenticate users.
JavaScript provides a facility to validate the form on the client-side so data processing
will be faster than server-side validation. Most web developers prefer JavaScript form
validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers and
more fields.
Example:
Program to validate the password length must be greater than 8 characters.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div style="text-align:center;background-color:#00f; margin:
100px;" >
<br><br>
<h2 >Login Page</h2>
<label for="name" >User name </label>
<input type="text" id="name" placeholder="Enter user
name" >
<br><br>
<label for="pwd" >Password</label>
<input type="password" id="pwd" placeholder="Enter
password" >
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
59
<br><br>
<input type="submit" value="Login"
onclick="pwdlength()">
<br><br>
</div>
<script>
function pwdlength()
{
const passwordInput =
document.getElementById('pwd');
const password = passwordInput.value;
if (password.length <= 8)
{
alert('Password must be greater than 8
characters');
passwordInput.focus(); // Focus on the password
field
return false; // Stop further processing
}
}
</script>
</body>
</html>
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
60
Output
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
61
</head>
<body>
<form>
<label for="n1">Num1</label>
<input type="text" id="n1" placeholder="Enter num1">
<br> <br>
<label for="n2">Num2</label>
<input type="text" id="n2" placeholder="Enter num2">
<br><br>
<input type="button" value="Add" onclick="add()">
<input type="button" value="sub" onclick="sub()">
</form>
<script>
//self invoking function
(function(){alert("Auto Invoked Function");})();
//event occurs
function add()
{
var
num1=parseInt(document.getElementById("n1").value);
var
num2=parseInt(document.getElementById("n2").value);
var sum=num1+num2;
alert("addition :"+sum);
}
function sub()
{
var
num1=parseInt(document.getElementById("n1").value);
var
num2=parseInt(document.getElementById("n2").value);
var sub=num1-num2;
alert("subtraction :"+sub);
}
//
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
62
function show()
{
alert("hi");
}
show();
</script>
</body>
</html>
Output
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology
63
____________________________________________________________________________
V.Veda Sri, CSE Faculty WebTechnology