JavaScript Basics and Applications Guide
JavaScript Basics and Applications Guide
SURESH
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
JavaScript (js)
JavaScript (js) is a light-weight object-oriented programming language which is used by
several websites for scripting the webpages. It is an interpreted, full-fledged programming
language that enables dynamic interactivity on websites when applied to an HTML
document. It was introduced in the year 1995 for adding programs to the webpages in the
Netscape Navigator browser. Since then, it has been adopted by all other graphical web
browsers.
Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog
box and prompt dialog box), Displaying clocks etc.
Example:
<script>
[Link](“welcome”);
</script>
You can also specify the <script > without specifying language.
Types of Scripts
[Link]-SideScripting
[Link]-SideScripting
1. Client-Side Scripting
Client-Side Scripting is an important part of the Dynamic HTML (DHTML).
JavaScript is the main client-side scripting language for the web.
The scripts are interpreted by the browser.
Client-Side scripting is used to make changes in the web page after they arrive at the
browser.
It is useful for making the pages a bit more interesting and user-friendly.
It provides useful gadgets such as calculators, clocks etc.
It enables interaction within a web page.
It is affected by the processing speed of the user's computer.
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
Operation of Client-Side Scripting
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Welcome to VIT Bhopal";
</script>
</body>
</html>
<p id="demo"></p>
<script>
let x = 10;
// Here x is 10
let x = 2;
// Here x is 2
[Link]("demo").innerHTML = x;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Redeclaring a Variable Using var</h2>
<p id="demo"></p>
<script>
var x = 10;
// Here x is 10
var x = 2;
// Here x is 2
[Link]("demo").innerHTML = x;
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
</script>
</body>
</html>
<html>
<body>
<h2>Welcome to JavaScript</h2>
<script>
[Link]("Hello JavaScript ");
</script>
</body>
</html>
<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello javascript");
}
</script>
</head>
<body>
<p>Welcome to Javascript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
[Link]
function msg(){
alert("Hello Javascript");
}
<html>
<head>
<script type="text/javascript" src="[Link]"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Prompt Example</title>
</head>
<body>
<script>
let name = prompt("Enter your name:");
[Link]("Hello " + name + "!");
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Add Numbers using Prompt</title>
</head>
<body>
<script>
let num1 = prompt("Enter first number:");
let num2 = prompt("Enter second number:");
let sum = parseFloat(num1) + parseFloat(num2);
[Link]("The sum is: " + sum);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Prompt with Condition</title>
</head>
<body>
<script>
let age = prompt("Enter your age:");
if (age >= 18) {
[Link]("You are eligible to vote!");
} else {
[Link]("You are not eligible to vote.");
}
</script>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<p>Never call [Link] after the document has finished loading.
It will overwrite the whole document.</p>
<script>
[Link](“hi”);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<script>
[Link](“hi”);
</script>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
</body>
</html>
<html>
<body>
<script>
var a=10;
var b=20;
var c=a+b;//It adds values of a and b variable
[Link](c);//prints sum of 10 and 20
</script>
</body>
</html>
<html>
<body>
<script>
/* It is multi line comment.
It will not be displayed */
[Link]("example of javascript multiline comment");
</script>
</body>
</html>
//Variables
<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
[Link](z);
</script>
</body>
</html>
<html>
<body>
<script>
var a=20;
if(a>10){
[Link]("value of a is greater than 10");
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
<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";
}
[Link](result);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
[Link](i + "<br/>")
}
</script>
</body>
</html>
JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).
Function
Function is a reusable code-block that will be executed whenever it is called.
Function is a great time saver.
It is used for performing repetitive tasks where you can call the same function
multiple times to get the same effect.
It allows code reusability.
JavaScript provides number of built-in functions.
Common Built-in Functions
Functions Description
isNan() Returns true, if the object is Not a Number.
Returns false, if the object is a number.
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
parseFloat If the string begins with a number, the function reads through the string until it finds the
(string) end of the number; cuts off the remainder of the string and returns the result.
If the string does not begin with a number, the function returns NaN.
parseInt If the string begins with an integer, the function reads through the string until it finds
(string) the end of the integer, cuts off the remainder of the string and returns the result.
If the string does not begin with an integer, the function returns NaN (Not a Number).
User-defined Functions
User-defined function means you can create a function for your own use. You can
create yourself according to your need.
In JavaScript, these functions are written in between the <HEAD> tag of the HTML
page.
Syntax:
function function_name()
{
//Code;
}
Example:
<html>
<body>
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
</body>
</html>
<html>
<body>
<script>
function getInfo(){
return "hello How r u?";
}
</script>
<script>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
[Link](getInfo());
</script>
</body>
</html>
<html>
<body>
<script type="text/javascript">
function getcube(){
var number=[Link]("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
</script>
</body>
</html>
<html>
<body>
<script type="text/javascript">
function add() // Function Declaration
{
var a = 2,b = 3;
var sum = 0;
sum = a+b;
[Link]("<b>Addition: </b>"+sum);
}
</script>
<p> Click the Button</p>
<input type="button" onClick="add()" value="Click"> //add() - Calling Function
</body>
</html>
Array
An array is an object that can store multiple values at once. For example,
const words = ['hello', 'world', 'welcome'];
Here, words is an array. The array is storing 3 values.
Syntax:
const array_name = [item1, item2, ...];
Create an Array
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<p id="demo"></p>
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<[Link];i++){
[Link](emp[i] + "<br/>");
[Link]("demo").innerHTML = emp;
} </script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<script>
let colors = new Array("red", "green", "blue");
[Link](colors);</script>
</body>
</html>
You can also store arrays, functions and other objects inside an array. For example,
const newData = [ {'task1': 'exercise'}, [1, 2 ,3], function hello() { [Link]('hello')} ];
You can use the built-in method push() and unshift() to add elements to an array.
The push() method adds an element at the end of the array. For example,
You can also add elements or change the elements by accessing the index value.
let dailyActivities = [ 'eat', 'sleep']; // this will add the new element 'exercise' at the 2 index
dailyActivities[2] = 'exercise'; [Link](dailyActivities); // ['eat', 'sleep', 'exercise']
Suppose, an array has two elements. If you try to add an element at index 3 (fourth element),
the third element will be undefined. For example,
let dailyActivities = [ 'eat', 'sleep']; // this will add the new element 'exercise' at the 3 index
dailyActivities[3] = 'exercise'; [Link](dailyActivities); // ["eat", "sleep", undefined,
"exercise"]
Basically, if you try to add elements to high indices, the indices in between will have
undefined value.
You can use the pop() method to remove the last element from an array. The pop() method
also returns the returned value. For example,
let dailyActivities = ['work', 'eat', 'sleep', 'exercise']; // remove the last element
[Link](); [Link](dailyActivities); // ['work', 'eat', 'sleep'] // remove the last
element from ['work', 'eat', 'sleep'] const removedElement = [Link](); //get
removed element [Link](removedElement); // 'sleep' [Link](dailyActivities); //
['work', 'eat']
If you need to remove the first element, you can use the shift() method. The shift() method
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
removes the first element and also returns the removed element. For example,
let dailyActivities = ['work', 'eat', 'sleep']; // remove the first element [Link]();
[Link](dailyActivities); // ['eat', 'sleep']
Array length
You can find the length of an element (the number of elements in an array) using
the length property. For example,
const dailyActivities = [ 'eat', 'sleep']; // this gives the total number of elements in an array
[Link]([Link]); // 2
Array Methods
In JavaScript, there are various array methods available that makes it easier to perform useful
calculations.
<html>
<body>
<script>
// Adding elements at the end of an array
// Declaring and initializing arrays
var arr = [ 10, 20, 30, 40, 50 ];
[Link](arr)
[Link]("After push <br>");
// push()
[Link](60);
[Link](arr)
[Link]("<br>");
// We can pass multiple parameters to the push()
// [10, 20, 30, 40, 50, 60, 70, 80, 90]
[Link](70, 80, 90);
[Link](1, 2);
[Link](arr+"<br>");
[Link]([Link]());
[Link](arr)
[Link]("<br>");
[Link]([Link]());
</script>
</body></html>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
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.
flatMap() It maps all array elements via mapping function, then flattens the result
into a new array.
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 provided
function conditions.
find() It returns the value of the first element in the given array that satisfies the
specified condition.
findIndex() It returns the index value of the first element in the given array that
satisfies the specified condition.
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 index
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
keys() It creates an iterator object that contains only the keys of the array, then
loops through these keys.
lastIndexOf() It searches the specified element in the given array and returns the index
of the last match.
map() It calls the specified function for every array element and returns the new
array
of() It creates a new array from a variable number of arguments, holding any
type of argument.
reduce(function, It executes a provided function for each value from left to right and
initial) reduces the array to a single value.
reduceRight() It executes a provided function for each value from right to left and
reduces the array to a single value.
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.
toString() It converts the elements of a specified array into string form, without
affecting the original array.
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.
Since arrays are objects, the array elements are stored by reference. Hence, when an array
value is copied, any change in the copied array will also reflect in the original array. For
example,
let arr = ['h', 'e']; let arr1 = arr; [Link]('l'); [Link](arr); // ["h", "e", "l"]
[Link](arr1); // ["h", "e", "l"]
You can also store values by passing a named key in an array. For example,
let arr = ['h', 'e']; [Link] = 'John'; [Link](arr); // ["h", "e"] [Link]([Link]); //
"John" [Link](arr['name']); // "John"
arr[i] = [];
let n = [9,5,4,3,7];
let x = n;
n = [];
[Link](x);
//Input for one dimensional array
var myarr=[];
var size = 5; // Array size
for(var a=0; a<size; a++)
{
<!DOCTYPE html>
<html>
<head>
<title>
How to take array input using JavaScript
</title>
</head>
<body style="text-align: center;">
<form>
<h1>Please enter data</h1>
<br>
<label for="Name">Name</label>
<input id="name" type="text">
<br>
<br>
<label for="Age">Age</label>
<input id="age" type="text">
<br>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
<br>
<label for="city">City</label>
<input id="City" type="text">
<br>
<br>
<input type="button" value="Save" onclick="savedata()">
<input type="button" value="Show data" onclick="displayData()">
<br>
</form>
<div id="display"></div>
<script type="text/javascript">
var arrCitys=new Array();
var arrNames=new Array();
var arrAges=new Array();
function savedata(){
var name = [Link]('name').value;
var city = [Link]('City').value;
var age = [Link]('age').value;
arrNames[[Link]]=name;
arrCitys[[Link]]=city;
arrAges[[Link]]=age; }
function displayData()
{
var content="<b>Data Entered by User :</b><br>";
content+= [...arrNames]+"</br>";
content+=[...arrAges]+"</br>";
content+=[...arrCitys]+"</br>";
[Link]('display').innerHTML = content;
}
</script>
</body>
</html>
Transpose Matrix
<html>
<head> <h3>Matrix Transpose</h3></head>
<body>
<script>
var r=prompt('Enter row value..: ' );
var c=prompt('Enter column value...: ' );
var arr = [];
for (var i = 0; i< r; i++) {
for(var j = 0; j< c; j++) {
arr[i] = [];
}
}
for (var i = 0; i < r; i++) {
for (var j = 0; j <c; j++) {
arr[i][j] = prompt('Enter array Element...: ' );
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
}
}
Functions Example
1.<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation, and returns the result:</p>
<p id="demo"></p>
<script>
function myFunction(p1, p2) {
return p1 * p2;
}
[Link]("demo").innerHTML = myFunction(4, 3);
</script>
</body>
</html>
2. <!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation and returns the result:</p>
<p id="demo"></p>
<script>
var x = myFunction(4, 3);
[Link]("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}
</script>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
</body>
</html>
3. <!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>Accessing a function without () will return the function definition instead of the function
result:</p>
<p id="demo"></p>
<script>
function toCelsius(f) {
return (5/9) * (f-32);
}
[Link]("demo").innerHTML = toCelsius;
</script>
</body>
</html>
4.<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object:
const person = {
firstName: "xyz",
lastName: "klm",
age: 20,
eyeColor: "black"
};
// Display some data from the object:
[Link]("demo").innerHTML =
[Link] + " is " + [Link] + " years old.";
</script>
</body>
</html>
HTML DOM methods are actions you can perform (on HTML Elements).
HTML DOM properties are values (of HTML Elements) that you can set or change.
<!DOCTYPE html>
<html>
<body>
<h2>My First Page</h2>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
In the example above the getElementById method used id="demo" to find the element.
The innerHTML property is useful for getting or replacing the content of HTML elements.
Method Description
Method Description
<html>
<body>
<p id="p2">Hello World!</p>
<script>
[Link]("p2").[Link] = "blue";
</script>
</body>
</html>
JavaScript Objects
Example:
[Link] person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
[Link] person = {};
// Add Properties
[Link] = "John";
[Link] = "Doe";
[Link] = 50;
[Link] = "blue";
3. // Create an Object
const person = new Object();
// Add Properties
[Link] = "John";
[Link] = "Doe";
[Link] = 50;
[Link] = "blue";
<!DOCTYPE html>
<html>
<body>
<h1>Creating JavaScript Objects</h1>
<h2>Using an Object Literal</h2>
<p id="demo"></p>
<script>
// Create an Object:
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
Built-in Objects
These objects are used for simple data processing in the JavaScript.
1. Math Object
Math object is a built-in static object.
It is used for performing complex math operations.
Methods Description
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
abs() Returns the absolute value of a number.
acos() Returns the arccosine (in radians) of a number.
ceil() Returns the smallest integer greater than or equal to a number.
cos() Returns cosine of a number.
floor() Returns the largest integer less than or equal to a number.
log() Returns the natural logarithm (base E) of a number.
max() Returns the largest of zero or more numbers.
min() Returns the smallest of zero or more numbers.
pow() Returns base to the exponent power, that is base exponent.
Math Methods
Date Object
Date is a data type.
Date object manipulates date and time.
Date() constructor takes no arguments.
Date object allows you to get and set the year, month, day, hour, minute, second and
millisecond fields.
Syntax:
var variable_name = new Date();
Example:
var current_date = new Date();
Date Methods
Methods Description
Date() Returns current date and time.
getDate() Returns the day of the month.
getDay() Returns the day of the week.
getFullYear() Returns the year.
getHours() Returns the hour.
getMinutes() Returns the minutes.
getSeconds() Returns the seconds.
getMilliseconds() Returns the milliseconds.
getTime() Returns the number of milliseconds since January 1, 1970 at
12:00 AM.
getTimezoneOffset() Returns the timezone offset in minutes for the current locale.
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
getMonth() Returns the month.
setDate() Sets the day of the month.
setFullYear() Sets the full year.
setHours() Sets the hours.
setMinutes() Sets the minutes.
setSeconds() Sets the seconds.
setMilliseconds() Sets the milliseconds.
setTime() Sets the number of milliseconds since January 1, 1970 at
12:00 AM.
3. String Object
String objects are used to work with text.
It works with a series of characters.
Syntax:
var variable_name = new String(string);
Example:
var s = new String(string);
String Properties
Properties Description
Length It returns the length of the string.
prototype It allows you to add properties and methods to an object.
constructor It returns the reference to the String function that created the object.
String Methods
Methods Description
charAt() It returns the character at the specified index.
charCodeAt() It returns the ASCII code of the character at the specified position.
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
concat() It combines the text of two strings and returns a new string.
indexOf() It returns the index within the calling String object.
match() It is used to match a regular expression against a string.
replace() It is used to replace the matched substring with a new substring.
search() It executes the search for a match between a regular expression.
slice() It extracts a session of a string and returns a new string.
split() It splits a string object into an array of strings by separating the string into
the substrings.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p id="demo"></p>
<script>
let text = "Vit Bhopal University";
let n = [Link](/Univ/i);
[Link]("demo").innerHTML = n;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<button onclick="replacefunc()">Try it</button>
<p id="demo">Welcome to VIT Bhopal University</p>
<script>
function replacefunc() {
let text = [Link]("demo").innerHTML;
[Link]("demo").innerHTML =
[Link](/u/i, "InterNational U");
}
</script>
</body>
</html>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p>Do a global search for "is" in a string:</p>
<p id="demo"></p>
<script>
let text = "Is 12 all 1212?";
let result = [Link](/12/g);
[Link]("demo").innerHTML = result;
</script>
</body>
</html>
Validation
<html>
<body>
<script>
function validateform(){
var name=[Link];
var password=[Link];
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if([Link]<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="[Link]" 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>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function matchpass(){
var firstpassword=[Link];
var secondpassword=[Link];
if(firstpassword==secondpassword){
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>
</head>
<body>
<form name="f1" action="[Link]" onsubmit="return matchpass()">
Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password" name="password2"/><br/>
<input type="submit">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script>
function validate(){
var num=[Link];
if (isNaN(num)){
[Link]("numloc").innerHTML="Enter Numeric value only";
return false;
}else{
return true;
}
}
</script>
</head>
<body>
<form name="myform" action="[Link]" onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>
</body>
</html>
<html lang="en">
<head>
<title>Form validation</title>
<script>
function printError(elemId, hintMsg) {
[Link](elemId).innerHTML = hintMsg;
}
function validateForm() {
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
var name = [Link];
var email = [Link];
var mobile = [Link];
var country = [Link];
var gender = [Link];
var hobbies = [];
var checkboxes = [Link]("hobbies[]");
for(var i=0; i < [Link]; i++) {
if(checkboxes[i].checked) {
[Link](checkboxes[i].value);
}
}
var nameErr = emailErr = mobileErr = countryErr = genderErr = true;
if(name == "") {
printError("nameErr", "Please enter name");
} else {
var regex = /^[a-zA-Z\s]+$/;
if([Link](name) === false) {
printError("nameErr", "Enter valid name");
} else {
printError("nameErr", "");
nameErr = false;
}
}
if(email == "") {
printError("emailErr", "enter your email");
} else {
var regex = /^\S+@\S+\.\S+$/;
if([Link](email) === false) {
printError("emailErr", "Please enter a valid email");
} else{
printError("emailErr", "");
emailErr = false;
}
}
if(mobile == "") {
printError("mobileErr", "Please enter mobile number");
} else {
var regex = /^[1-9]\d{9}$/;
if([Link](mobile) === false) {
printError("mobileErr", "Please enter a valid mobile number");
} else{
printError("mobileErr", "");
mobileErr = false;
}
}
if(country == "Select") {
printError("countryErr", "Please select country");
} else {
printError("countryErr", "");
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
countryErr = false;
}
if(gender == "") {
printError("genderErr", "Please select gender");
} else {
printError("genderErr", "");
genderErr = false;
}
if((nameErr || emailErr || mobileErr || countryErr || genderErr) == true) {
return false;
} else {
var dataPreview = "You've entered the following details: \n" +
"Full Name: " + name + "\n" +
"Email Address: " + email + "\n" +
"Mobile Number: " + mobile + "\n" +
"Country: " + country + "\n" +
"Gender: " + gender + "\n";
if([Link]) {
dataPreview += "Hobbies: " + [Link](", ");
}
alert(dataPreview);
}
};
</script>
</head>
<body>
<form name="contactForm" onsubmit="return validateForm()"
action="/examples/actions/[Link]" method="post">
<h2>Application Form</h2>
<div class="row">
<label>Full Name</label>
<input type="text" name="name">
<div class="error" id="nameErr"></div>
</div>
<div class="row">
<label>Email Address</label>
<input type="text" name="email">
<div class="error" id="emailErr"></div>
</div>
<div class="row">
<label>Mobile Number</label>
<input type="text" name="mobile" maxlength="10">
<div class="error" id="mobileErr"></div>
</div>
<div class="row">
<label>Country</label>
<select name="country">
<option>Select</option>
<option>Australia</option>
<option>India</option>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
<option>United States</option>
<option>United Kingdom</option>
</select>
<div class="error" id="countryErr"></div>
</div>
<div class="row">
<label>Gender</label>
<div class="form-inline">
<label><input type="radio" name="gender" value="male"> Male</label>
<label><input type="radio" name="gender" value="female"> Female</label>
</div>
<div class="error" id="genderErr"></div>
</div>
<div class="row">
<label>Hobbies <i>(Optional)</i></label>
<div class="form-inline">
<label><input type="checkbox" name="hobbies[]" value="sports"> Sports</label>
<label><input type="checkbox" name="hobbies[]" value="movies"> Movies</label>
<label><input type="checkbox" name="hobbies[]" value="music"> Music</label>
</div>
</div>
<div class="row">
<input type="submit" value="Submit">
</div>
</form>
</body>
</html>
Regular Expressions
Syntax:
/pattern/modifiers;
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p id="demo"></p>
<script>
let text = "Vit University!";
let n = [Link](/VIT/i);
[Link]("demo").innerHTML = n;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Regex Example</title>
</head>
<body>
<script>
let text = "I love JavaScript!";
let pattern = /JavaScript/; // Regular Expression
let result = [Link](text); // test() returns true or false
[Link]("Pattern found: " + result);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
<title>Find Digits</title>
</head>
<body>
<script>
let text = "My roll number is 12345 and ID is 6789.";
let digits = [Link](/\d+/g); // \d+ means one or more digits
[Link]("Digits found: " + digits);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Replace using Regex</title>
</head>
<body>
<script>
let text = "I love JavaScript. JavaScript is fun!";
let newText = [Link](/JavaScript/g, "Python"); // g = global
[Link](newText);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit vit</p>
<script>
function myFunction() {
let text = [Link]("demo").innerHTML;
[Link]("demo").innerHTML =
[Link](/vit/i, "vit university");
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p id="demo"></p>
<script>
let text = "Is this all there is?";
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
let result = [Link](/[he]/g);
[Link]("demo").innerHTML = result;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p id="demo"></p>
<script>
let text = "Rs.1000";
let result = [Link](/\d/g);
[Link]("demo").innerHTML = result;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p>Search for an "e" in the next paragraph:</p>
<p id="para1">The best things in life are free!</p>
<p id="demo"></p>
<script>
let text = [Link]("para1").innerHTML;
const pattern = /o/;
[Link]("demo").innerHTML = [Link](text);
</script>
</body>
</html>
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:
mouseover onmouseover When the cursor of the mouse comes over the
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
element
mousedown onmousedown When the mouse button is pressed over the element
Mouseup onmouseup When the mouse button is released over the element
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
Form events:
Change onchange When the user modifies or changes the value of a form
element
Window/Document events
Event Event Description
Performed Handler
Load onload When the browser finishes the loading of the page
Unload onunload When the visitor leaves the current webpage, the browser
unloads it
Resize onresize When the visitor resizes the window of the browser
Click Event
1. <html>
2. <head> Javascript Events </head>
3. <body>
4. <script language="Javascript" type="text/Javascript">
5. <!--
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
6. function clickevent()
7. {
8. [Link]("This is Javascript");
9. }
10. //-->
11. </script>
12. <form>
13. <input type="button" onclick="clickevent()" value="Who's this?"/>
14. </form>
15. </body>
16. </html>
MouseOver Event
1. <html>
2. <head>
3. <h1> Javascript Events </h1>
4. </head>
5. <body>
6. <script language="Javascript" type="text/Javascript">
7. <!--
8. function mouseoverevent()
9. {
10. alert("This is Javascript");
11. }
12. //-->
13. </script>
14. <p onmouseover="mouseoverevent()"> Keep cursor over me</p>
15. </body>
16. </html>
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. [Link]("input1").[Link]=" aqua";
11. }
12. //-->
13. </script>
14. </body>
15. </html>
Keydown Event
1. <html>
2. <head> Javascript Events</head>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
3. <body>
4. <h2> Enter something here</h2>
5. <input type="text" id="input1" onkeydown="keydownevent()"/>
6. <script>
7. <!--
8. function keydownevent()
9. {
10. [Link]("input1");
11. alert("Pressed a key");
12. }
13. //-->
14. </script>
15. </body>
16. </html>
Load event
1. <html>
2. <head>Javascript Events</head>
3. </br>
4. <body onload="[Link]('Page successfully loaded');">
5. <script>
6. <!--
7. [Link]("The page is loaded successfully");
8. //-->
9. </script>
10. </body>
11. </html>
An exception signifies the presence of an abnormal condition which requires special operable
techniques. In programming terms, an exception is the anomalous code that breaks the
normal flow of the code. Such exceptions require specialized programming constructs for its
execution.
In programming, exception handling is a process or method used for handling the abnormal
statements in the code and executing them. It also enables to handle the flow control of the
code/program. For handling the code, various handlers are used that process the exception
and execute the code. For example, the Division of a non-zero value with zero will result into
infinity always, and it is an exception. Thus, with the help of exception handling, it can be
executed and handled.
In exception handling:
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
A throw statement is used to raise an exception. It means when an abnormal condition occurs,
an exception is thrown using throw.
The thrown exception is handled by wrapping the code into the try…catch block. If an error
is present, the catch block will execute, else only the try block statements will get executed.
Thus, in a programming language, there can be different types of errors which may disturb
the proper execution of the program.
Types of Errors
Error Object
When a runtime error occurs, it creates and throws an Error object. Such an object can be
used as a base for the user-defined exceptions too. An error object has two properties:
Although Error is a generic constructor, there are following standard built-in error types or
error constructors beside it:
1. EvalError: It creates an instance for the error that occurred in the eval(), which is a
global function used for evaluating the js string code.
2. InternalError: It creates an instance when the js engine throws an internal error.
3. RangeError: It creates an instance for the error that occurs when a numeric variable or
parameter is out of its valid range.
4. ReferenceError: It creates an instance for the error that occurs when an invalid
reference is de-referenced.
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
5. SyntaxError: An instance is created for the syntax error that may occur while parsing
the eval().
6. TypeError: When a variable is not a valid type, an instance is created for such an
error.
7. URIError: An instance is created for the error that occurs when invalid parameters are
passed in encodeURI() or decodeURI().
o throw statements
o try…catch statements
o try…catch…finally statements.
JavaScript try…catch
try{} statement: Here, the code which needs possible error testing is kept within the try block.
In case any error occur, it passes to the catch{} block for taking suitable actions and handle
the error. Otherwise, it executes the code written within.
catch{} statement: This block handles the error of the code by executing the set of statements
written within the block. This block contains either the user-defined exception handler or the
built-in handler. This block executes only when any error-prone code needs to be handled in
the try block. Otherwise, the catch block is skipped.
Syntax:
1. try{
2. expression; } //code to be written.
3. catch(error){
4. expression; } // code for handling the error.
try…catch example
1. <html>
2. <head> Exception Handling</br></head>
3. <body>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
4. <script>
5. try{
6. var a= ["34","32","5","31","24","44","67"]; //a is an array
7. [Link](a); // displays elements of a
8. [Link](b); //b is undefined but still trying to fetch its value. Thus catch block will be
invoked
9. }catch(e){
10. alert("There is error which shows "+[Link]); //Handling error
11. }
12. </script>
13. </body>
14. </html>
Throw Statement
Throw statements are used for throwing user-defined errors. User can define and throw their
own custom errors. When throw statement is executed, the statements present after it will not
execute. The control will directly pass to the catch block.
Syntax:
1. throw exception;
try…catch…throw syntax
1. try{
2. throw exception; // user can define their own exception
3. }
4. catch(error){
5. expression; } // code for handling exception.
With the help of throw statement, users can create their own errors.
try…catch…finally statements
Finally is an optional block of statements which is executed after the execution of try and
catch statements. Finally block does not hold for the exception to be thrown. Any exception
is thrown or not, finally block code, if present, will definitely execute. It does not care for the
output too.
Syntax:
1. try{
2. expression;
3. }
4. catch(error){
5. expression;
6. }
7. finally{
8. expression; } //Executable code
try…catch…finally example
1. <html>
2. <head>Exception Handling</head>
3. <body>
4. <script>
5. try{
6. var a=2;
7. if(a==2)
8. [Link]("ok");
9. }
10. catch(Error){
11. [Link]("Error found"+[Link]);
12. }
13. finally{
14. [Link]("Value of a is 2 ");
15. }
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
16. </script>
17. </body>
18. </html>
JSON
{"name":"John"}
JavaScript
{name:"John"}
person = {name:"John", age:31, city:"New York"};
JSON data can easily be sent between computers, and used by any programming language.
JavaScript has a built in function for converting JSON strings into JavaScript objects:
[Link]()
JavaScript also has a built in function for converting an object into a JSON string:
[Link]()
Javascript object
<!DOCTYPE html>
<html>
<body>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
<h2>Access a JavaScript object</h2>
<p id="demo"></p>
<script>
const myObj = {name:"John", age:30, city:"New York"};
[Link]("demo").innerHTML = [Link];
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Create a JSON string from a JavaScript object.</h2>
<p id="demo"></p>
<script>
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = [Link](obj);
[Link]("demo").innerHTML = myJSON;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Looping JavaScript Object Values</h2>
<p id="para1"></p>
<p id="para2"></p>
<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = [Link](myJSON);
let str1 = "";
let str2 = "";
for (const x in myObj) {
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
str1 += x + ", ";
str2 += myObj[x] + ", ";
}
[Link]("para1").innerHTML = str1;
[Link]("para2").innerHTML = str2;
</script>
</body>
</html>
JSON Arrays
JavaScript Array
<!DOCTYPE html>
<html>
<body>
<h2>Creating an Array from a Literal</h2>
<p id="demo"></p>
<script>
const myArray = ["Ford", "BMW", "Fiat"];
[Link]("demo").innerHTML = myArray;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Creating an Array from JSON</h2>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const myArray1 = ["Ford", "BMW", "Fiat"];
[Link]("demo1").innerHTML = myArray1;
const myJSON = '["Ford", "BMW", "Fiat"]';
const myArray2 = [Link](myJSON);
[Link]("demo2").innerHTML = myArray2;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>Access an Array by Index</h1>
<p id="demo"></p>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
<script>
const myJSON = '["Ford", "BMW", "Fiat"]';
const myArray = [Link](myJSON);
[Link]("demo").innerHTML = myArray[0];
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Looping an Array</h2>
<p id="demo"></p>
<script>
const myJSON = '{"cars":["Ford", "BMW", "Fiat","Benz"]}';
const myObj = [Link](myJSON);
let text = "";
for (let i in [Link]) {
text += [Link][i] + ", ";
}
[Link]("demo").innerHTML = text;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Looping an Array</h2>
<p id="demo"></p>
<script>
const myJSON = '{"cars":["Ford", "BMW", "Fiat","Benz"]}';
const myObj = [Link](myJSON);
let text = "";
for (let i = 0; i < [Link]; i++) {
text += [Link][i] + ", ";
}
[Link]("demo").innerHTML = text;
</script>
</body>
</html>
jQuery
jQuery is a lightweight open-source JavaScript library that simplifies manipulating
the Document Object Model (DOM), handling events, and creating dynamic web
experiences.
jQuery is to simplify the usage of JavaScript on websites.
jQuery simplifies complex JavaScript tasks with single-line methods, it makes your code
more readable and maintainable.
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
Include the jQuery Library:
1. Using jQuery Library Content Delivery Network (CDN) in your HTML project.
<script src="[Link]
2. Once the library is included, you can write jQuery code within <script> tags. jQuery code
typically follows a specific syntax:
<script> $(document).ready(function() { // Your jQuery code here });</script>
The $(document).ready(function() { ... }) function ensures your code executes only after the
document is fully loaded, preventing errors.
<!DOCTYPE html>
<html>
<head>
<script src=
"[Link]
</script>
<script>
$(document).ready(function () {
$("h1").hover(
function () {
$(this).css(
"color",
"green"
);
},
function () {
$(this).css(
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
"color",
"red"
);
}
);
});
</script>
</head>
<body>
<h1>VIT Bhopal University</h1>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="[Link]
</head>
<body>
<h2>Show HTML Elements</h2>
<p id="01" style="display:none">Hello World!</p>
<p id="02" style="display:none">Hello Sweden!</p>
<p id="03" style="display:none">Hello Japan!</p>
<script>
$(document).ready(function() {
$("#02").show();
});
</script>
</body>
</html>
[Link](jquery Example)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Employee Details</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
th, td {
padding: 10px;
text-align: left;
}
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h2>Employee Details</h2>
<table id="employeeTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Department</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<!-- Employee details will be inserted here by jQuery -->
</tbody>
</table>
<!-- Include jQuery -->
<script src="[Link]
<script src="[Link]"></script>
</body>
</html>
[Link]
$(document).ready(function() {
var employees = [
{ id: 1, name: "John Doe", department: "Engineering", salary: "$100,000" },
{ id: 2, name: "Jane Smith", department: "Marketing", salary: "$90,000" },
{ id: 3, name: "Samuel Johnson", department: "Sales", salary: "$80,000" },
{ id: 4, name: "Chris Lee", department: "Support", salary: "$70,000" }
];