0% found this document useful (0 votes)
1 views127 pages

JavaScript

The document provides an overview of JavaScript, emphasizing its role in client-side scripting for dynamic web pages, enhancing usability and efficiency. It contrasts client-side scripting with server-side programming, highlighting JavaScript's features such as variable declaration, data types, type conversion, and operators. Additionally, it covers array manipulation, string methods, and practical programming examples, illustrating JavaScript's versatility across various applications.

Uploaded by

Basha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views127 pages

JavaScript

The document provides an overview of JavaScript, emphasizing its role in client-side scripting for dynamic web pages, enhancing usability and efficiency. It contrasts client-side scripting with server-side programming, highlighting JavaScript's features such as variable declaration, data types, type conversion, and operators. Additionally, it covers array manipulation, string methods, and practical programming examples, illustrating JavaScript's versatility across various applications.

Uploaded by

Basha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 127

JavaScript

Language Fundamentals

8/22/2025
Client Side Scripting

CS380 2
Why use client-side
programming?
Server scripting languages(PHP) already allows us to
create dynamic web pages. Why also use client-side
scripting?
• client-side scripting (JavaScript) benefits:
• usability: can modify a page without having to post back
to the server (faster UI)
• efficiency: can make small, quick changes to page
without waiting for server
• event-driven: can respond to user actions like clicks and
key presses

CS380 3
Server-side programming?
• server-side programming (PHP) benefits:
• security: has access to server's private data; client can't
see source code
• compatibility: not subject to browser compatibility
issues
• power: can write files, open connections to servers,
connect to databases, ...

CS380 4
About JavaScript
• JavaScript is not Java, or even related to Java
• The original name for JavaScript was “LiveScript”
• The name was changed when Java became popular
• Statements in JavaScript resemble statements in Java,
because both languages borrowed heavily from the C
language
• JavaScript should be fairly easy for Java programmers to learn
• However, JavaScript is a complete, full-featured, complex language
• JavaScript is seldom used to write complete “programs”
• Instead, small bits of JavaScript are used to add functionality to
HTML pages
• JavaScript is often used in conjunction with HTML “forms”
• JavaScript is reasonably platform-independent
Javascript everywhere
• Popular programming language
• Can be used in any application in any platform
• Web Application, Mobile Application Machine learning
etc
• JS Engine is available in most of the browsers

10/25/2025
Hello world program

Program  machine code

prg1.js – in any editor


Console.log(“Hello World”);

Execute ?

10/25/2025
Execution
• In browser console (without html and css) – JS engine
• Inside html JS engine
• Command prompt (without browser)
• Need node js (can run javascript on OS)
• Runtime environment
• Download
• Check node - - version
• To run- node f1.js
• To quit – CTRLC twice

10/25/2025
Variables – let
• let data = 10 create a variable using let
• let name = “XYZ”

• Constants
• Const data=100

• What is var ?

10/25/2025
var
• Variables declared with the var keyword can NOT
have block scope.
• Variables declared inside a { } block can be
accessed from outside the block.
• Redeclaring a variable using the var keyword can
impose problems.
• Redeclaring a variable inside a block will also
redeclare the variable outside the block:

10/25/2025
• Redeclaring a variable using the let keyword can
solve this problem.

• Redeclaring a variable inside a block will not


redeclare the variable outside the block:
• Block scoped
• Variables defined with let can not be redeclared.

10/25/2025
Egs (redeclaration and scope)

• let x = "John Doe"; • var x = "John Doe";

let x = 0; var x = 0;

• var x = 10;
// Here x is 10
• let x = 10;
// Here x is 10
{
{ var x = 2;
let x = 2; // Here x is 2
// Here x is 2 }
}
// Here x is 2
// Here x is 10

10/25/2025
let x=10 var x=10
{ {
let x="hello" var x="hello"
console.log(x) console.log(x)
} }
console.log(x) Console.log(x)

10/25/2025
Data Types
• Primitive – Number(float), String, Boolean, Null,
Undefined, Symbol
• Object – not a primitive type

10/25/2025
Number
• typeof X
• Underscores for long numbers(instead of comma)
• Infinity, -infinity
• MAX_VALUE
• Bigint – add n at the end of the number
• Let x= bigint(123232323423552)
• let x = 9999999999999999;
let y = 9999999999999999n;

10/25/2025
Strings
• Single quote, double quote
• Escape sequences
• Let s= ‘Sdnfksdnfjksndk \‘sscdfbsdhbfsbfd’

10/25/2025
boolean
• True
• False

let x=Boolean(1 > 9)


console.log(x)

10/25/2025
undefined,Empty
• undefined – undefined datatype
let car;
console.log(car)
Empty
let car = "";
console.log(car)
console.log(typeof car)

10/25/2025
Type Conversion
• Convert one datatype to another
• Explicit Conversion
• Let x= number(“100”)

10/25/2025
• Converting Strings to Numbers
• Converting Numbers to Strings
• Converting Dates to Numbers
• Converting Numbers to Dates
• Converting Booleans to Numbers
• Converting Numbers to Booleans

10/25/2025
Converting Strings to
Numbers
• The global method Number() converts a variable (or a value) into a
number.

• A numeric string (like "3.14") converts to a number (like 3.14).

• An empty string (like "") converts to 0.


• Number("3.14")
Number(Math.PI)
Number(" ")
Number("")

• A non numeric string (like "John") converts to


NaN (Not a Number).
10/25/2025
• Converting Numbers to Strings
• The global method String() can convert numbers to
strings.

• It can be used on any type of numbers, literals,


variables, or expressions:
• String(x)
• String(123)
String(100 + 23)

10/25/2025
• Converting Dates to Strings
• console.log(String(Date()))
• Output: Mon Aug 19 2024 14:44:35
GMT+0530 (India Standard Time)

10/25/2025
10/25/2025
• Converting Booleans to Numbers
• The global method Number() can also convert
booleans to numbers.
let x= Number(false) // returns 0
let y=Number(true)
console.log(x)
console.log(y)

10/25/2025
• Converting Booleans to Strings
• The global method String() can convert booleans to
strings.

• String(false) // returns "false"


• String(true) // returns "true"

10/25/2025
Automatic Type
Conversion
• When JavaScript tries to operate on a "wrong" data
type, it will try to convert the value to a "right" type.

5 + null // returns 5 because null


is converted to 0
"5" + null // returns "5null" because null
is converted to "null"
"5" + 2 // returns "52" because 2 is
converted to "2"
"5" - 2 // returns 3 because "5"
is converted to 5
"5" * "2" // returns 10 because "5"
and "2" are converted to 5 and 2

10/25/2025
Type Coercion
• Operating with two different datatypes
• Decide the operation
• 2 +” sample” -> string operation
• 2- sample -> number operation
• Any type to Boolean
• truthy values- all values are converted as true
• except undefined, null, Nan, 0, “ “, false – falsy values
• true + true =?
• Let x = Boolean(“”)

10/25/2025
Operators
• Arithmetic Operators - +, -, *, /, %, **
• Shorthand operators +=, -= …
• preincrement
• postincrement
• Eg n=5
• x= n++ x=5, n=6
• n = ++x x=6 n=6
• Value of n and x after the above statements?

10/25/2025
Operators - Arithmetic
• Arithmetic Operators - +, -, *, /, %
• Shorthand operators +=, -= …
• preincrement
• postincrement
• Eg n=5
• x= n++
• n = ++x
• Value of n and x after the above statements?
• x= 6 n=6
10/25/2025
Relational Operators
• <, >, <=, >=, ==, ===(data and type)
• Output is a Boolean value
• Compare
• number and number
• String and string
• String and number

10/25/2025
Other operators
• Logical operators:
&& || ! (&& and || are short-circuit operators)
• Bitwise operators:
& | ^ ~ << >> >>>
• Assignment operators:
+= -= *= /= %= <<= >>= >>>= &=
^= |=
• String operator:
+
• The conditional operator:
condition ? value_if_true : value_if_false

• Additional operators:
new typeof void delete
10/25/2025
Comments
• Comments are as in C or Java:
• Between // and the end of the line
• Between /* and */
• Java’s javadoc comments, /** ... */, are treated just
the same as /* ... */ comments; they have no special
meaning in JavaScript
for loop (same as Java)-
output?
var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
}
var s1 = "hello";
JS
var s2 = "";
for (var i = 0; i < s1.length; i++) {
s2 += s1.charAt(i) + s1.charAt(i);
}

CS380 34
for loop (same as Java)
var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
}
var s1 = "hello";
JS
var s2 = "";
for (var i = 0; i < s1.length; i++) {
s2 += s1.charAt(i) + s1.charAt(i);
}
// s2 stores "hheelllloo"

CS380 35
while loops (same as Java)
while (condition) {
statements;
}
do {
statements;
} while (condition);
 break and continue keywords also behave as
in Java

CS380 36
Array – different ways to
create an array
• You can use an array literal:
var colors = ["red", "green", "blue"];
• You can use new Array() to create an empty
array:
– var colors = new Array();
• You can add elements to the array later:
colors[0] = "red"; colors[2] = "blue";
colors[1]="green";
• You can use new Array(n) with a single numeric
argument to create an array of that size
– var colors = new Array(3);
• You can use new Array(…) with two or more
arguments to create an array containing those
values:
Arrays
var name = []; // empty array
var name = [value, value, ..., value]; //
pre-filled
name[index]
var ducks = = value; //
["Huey", store element
"Dewey", "Louie"];
var stooges = []; // stooges.length is 0
JS
stooges[0] = "Larry"; // stooges.length is 1
stooges[1] = "Moe"; // stooges.length is 2
stooges[4] = "Curly"; // stooges.length is 5
stooges[4] = "Shemp"; // stooges.length is 5

CS380 38
Array methods
var a = ["Stef", "Jason"]; // Stef, Jason
a.push("Brian"); // Stef, Jason, Brian
a.unshift("Kelly"); // Kelly, Stef, Jason, Brian
a.pop(); // Kelly, Stef, Jason
a.shift(); // Stef, Jason
a.sort(); // Jason, Stef
 array serves as many data structures: list, queue, stack, ...
 methods: concat, join, pop, push, reverse, shift, slice, sort,
splice, toString, unshift
 push and pop add/remove from back
 unshift and shift add/remove from front
 shift and pop return the element that is removed
 slice returns a piece of the array but it doesn’t affect the
original array. splice changes the original array by removing,
replacing, or adding values and returns the affected values. 39
String type
var s = "Connie Client";
var fName = s.substring(0, s.indexOf(" "));
// "Connie"
var len = s.length; // 13
var s2 = 'Melvin Merchant';

• methods: charAt, charCodeAt, fromCharCode, indexOf, lastIndexOf,


replace, split, substring, toLowerCase, toUpperCase
• charAt returns a one-letter String (there is no char type)
• length property (not a method as in Java)

let text = "Hello


World!";
let result =
40
text.toUpperCase();
• let text = "Hello planet earth, you
are a great planet.";
let result=text.lastIndexOf("planet
");

• let text = "Visit Tesla!";


let result =
text.replace(“Tesla", “Amrita");

10/25/2025
More about String
 escape sequences behave as in Java: \' \" \& \
n \t \\
 converting between numbers and Strings:
var count = 10;
var s1 = "" + count; // "10"
var s2 = count + " bananas, ah ah ah!"; // "10 bananas, ah ah ah!"
var n1 = parseInt("42 is the answer"); // 42
var n2 = parseFloat("booyah"); // NaN

• accessing the letters of a String:


var firstLetter = s[0]; // fails in IE
var firstLetter = s.charAt(0); // does work in IE
var lastLetter = s.charAt(s.length - 1);
CS380 42
Splitting strings: split and
join
var s = "the quick brown fox";
var a = s.split(" "); // ["the", "quick", "brown", "fox"]
a.reverse(); // ["fox", "brown", "quick", "the"]
s = a.join("!"); // "fox!brown!quick!the"

 split breaks apart a string into an array using a


delimiter
 can also be used with regular expressions
 join merges an array into a single string,
placing a delimiter between them
43
Arrays
• var cars =
[“Audi", “Benz", “Jaguar"];
• Console.log(cars[0])

• In JavaScript, arrays use numbered


indexes.

10/25/2025
1.Write a JavaScript program that accepts a number as input
and inserts dashes (-) between each even and odd number
combination.
For example, if you accept 025478 the output should be 02-
54-78.

2.Write a JavaScript program to find a pair of elements


(indices of the two numbers) in a given array whose difference
equals a specific target number.
Input: numbers= [10,20,10,40,50,60,70], target=50
Output: [5, 0] [5, 2] [6,1]

10/25/2025
• npm install prompt-sync

• const prompt = require("prompt-


sync")();

let a = prompt("enter a number: ")
• console.log(a)

10/25/2025
Addition of 2 numbers
const prompt = require("prompt-sync")();

let a = Number(prompt("Enter first number:"));


let b = Number(prompt("Enter second number:"));
let sum = a + b;
console.log("Sum is: " + sum);

10/25/2025
JAVASCRIPT programs

• 1.to check whether number is even or odd


• 2. Reverse a input string
• 3.Check whether a string is palindrome or not
• 4.Find largest number in an array
• 5.Sum of all elements in an array
• 6.Reverse an array without using reverse function

10/25/2025
JavaScript Classes are
templates for JavaScript
Objects.

10/25/2025
this is a special keyword in JavaScript that refers to the object that is
currently using the code.

10/25/2025
10/25/2025
class Car {
constructor(name, year) { //Initializing object
this.name = name; property
this.year = year;
}
}
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);
console.log(myCar1.name)
10/25/2025
10/25/2025
Class methods program
class Person{
constructor(name,year)
{
this.name=name;
this.year=year;
}
age(){
const date = new Date();
return date.getFullYear() - this.year;
}
}
const car=new Person('glanza',2024)
console.log("My car is " + car.age() + " years old.");

10/25/2025
Objects – not primitive
ones
• To represent real-world entity in the virtual world.
• let student = { } // empty object
• let student = {
key1 : value1,
key2: value2 } //like dictionary
}
const person = {firstName:"John",
lastName:"Doe", age:50, eyeColor:"blue"};
• Access all or particular property
• Student or student.key1 or
student[‘key1’]
10/25/2025
Objects(Other way of
creating an object)
const car={name:"glanza",year:2024};
const car1={name:"kiger",year:2022};
console.log(car.name)
console.log("I purchased my second
car in the year",car1.year)

10/25/2025
Arrays and objects
• Arrays are objects – special objects
• In JavaScript, objects use named
indexes whereas Arrays use
numbered indexes.
• car = { myCar: "Saturn", 7: "Mazda" }
– car[7] is the same as car.7
– car.myCar is the same as car["myCar"]
• If you know the name of a property, you
can use dot notation: car.myCar
• If you don’t know the name of a
property, but you have it in a variable
(or can compute it), you must use array
• console.log(student.name)
• console.log(student[‘name’]);
• prop1= ‘name’
• console.log(student[prop1]) // cannot use dot
operator if it is variable
• Add functions

10/25/2025
Complex objects
• Object within an object
• let boxOfStuff = {
book: "Object-Oriented JavaScript",
smallerBox:
{ stuff: ["pencils", "pens"],
smallestBox: { stuff: ["paper clips",
"thumbtacks"] }
}
};
console.log(boxOfStuff.smallerBox.smallestBox.st
uff)
10/25/2025
• console.log(boxOfStuff.smallerBox.smalle
stBox.stuff);
// Output: ["paper clips", "thumbtacks"]

If paperclips to be accessed?

10/25/2025
• console.log(boxOfStuff.smallerBox.smallestBox.stuff);
// Output: ["paper clips", "thumbtacks"]

If paperclips to be accessed?

console.log(boxOfStuff.smallerBox.smallestBox.stuff[0]
);
Or
console.log(boxOfStuff['smallerBox']['smallestBox']
['stuff'][0]);
// Output: "paper clips"

10/25/2025
Complex Objects
• Examples( with function, variable)
– car = {myCar: "Saturn", 7: "Mazda",
getCar: CarTypes("Honda"), special: Sales}
• The fields are myCar, getCar, 7 (this is a legal
field name) , and special
• "Saturn" and "Mazda" are Strings
• CarTypes is a function call
• Sales is a variable you defined earlier
• Example use: document.write("I own a " +
car.myCar);
Three ways to create an
object
• You can use an object literal:
– var course = { number: "CIT597", teacher="Dr. Dave" }
• You can use new to create a “blank” object, and
add fields to it later:
– var course = new Object();
course.number = "CIT597";
course.teacher = "Dr. Dave";
• You can write and use a constructor:
– function Course(n, t) { // best placed in <head>
this.number = n;
this.teacher = t;
}
– var course = new Course("CIT597", "Dr. Dave");
• Write a javascript program to print key names in
javascript objects

10/25/2025
• console.log(Object.keys(Course));
• Object.values(Course) ?

10/25/2025
The for…in statement to
Iterate on object’s properties
• You can loop through all the properties of an object with
‘for’ (variable in object) statement;
• Example: for (var prop in course) {
console.log(prop + ": " + course[prop]);
}
• for (let key in student)
{ console.log(key, student[key]) // not dot
operator

10/25/2025
const person = {fname:"John", lname:"Doe",
age:25};

let text = "";


for (let x in person) {
text += person[x];
}
console.log(text)

10/25/2025
const numbers = [45, 4, 9, 16, 25];

let txt = "";


for (let x in numbers) {
txt += numbers[x];
}
console.log(txt)

10/25/2025
The with statement
The with keyword is used as a kind of shorthand for referencing
an object's properties or methods.
The object specified as an argument to ‘with’ becomes the default
object for the duration of the block that follows.
The properties and methods for the object can be used
without naming the object.
Syntax
The syntax for “with” object is as follows −

with (object){
properties used without the object name and dot
}

10/25/2025
eg
function addPrice(amount){
with(this){
price = amount;
}
}
function book(title, author){
this.title = title;
this.author = author;
this.price = 0;
this.addPrice = addPrice; // Assign that method as property.
}

mybook = new book("FSD", "Chris");


mybook.addPrice(1000);
Book1=new book("TOC","Christ");
Book1.addPrice(500);
console.log(mybook)
10/25/2025
console.log(Book1)
Create a simplified online bookstore
inventory management system. The
system needs to handle book information,
manage inventory, and provide a way to
search for books. Create a JavaScript
program that represents this scenario.
Create a book or array of book objects…
For loop for display
For loop for searching
Update a particular books quantity
10/25/2025
• let books = [ { title: "The Great Gatsby",
author: "F. Scott Fitzgerald", genre:
"Classic", quantity: 10 }, { title: "To Kill a
Mockingbird", author: "Harper Lee",
genre: "Fiction", quantity: 15 }, { title:
"1984", author: "George Orwell", genre:
"Dystopian", quantity: 8 }, // Add more
books as needed ];

10/25/2025
Now use html command to include
the javascript output in html
• Use alert
or

• document.write("<h1>Hello World!</h1>") ;

or
• Document.getelementbyID(“
id”).innerHTML =Course[0]

10/25/2025
Functions
• Reuse the set of statements
• Dividing the tasks into small tasks.
• function message()
{console.log(“Welcome”); }

message()
message()

10/25/2025
User input in nodejs

10/25/2025
Compare 2 no’s(Run-time input)
const readline = require("readline-sync");
function max(x,y)
{ if (x>y)
return x;
else
return y;
}
let x1 = Number(readline.question("Enter x value:"));
let y1 = Number(readline.question("enter y value:"));

console.log("the biggest number is",max(x1,y1));

10/25/2025
More about Functions
• Functions are objects with method called “( )”
• A property of an object may be a function (=method)
• function max(x,y) { if (x>y) return x; else return y;};
• max.description = “return the maximum of two arguments”;
• Local declarations may appear in function body
• Call can supply any number of arguments
• functionname.length : # of arguments in definition
• functionname.arguments.length : # arguments in call
• Basic types are passed by value, objects by reference
• “Anonymous” functions
• (function (x,y) {return x+y}) (2,3);

slide 77
Anonymous functions:In JavaScript, an
anonymous function is a function
without a name.

10/25/2025
Arrow functions
let add = function(x,y)
{return x+y;}
let sum = add(2,3)
let result = sum(4,5);

10/25/2025
Arrow functions
let add =(x,y) => {return x+y;}
let sum = add(2,3)
Console.log(sum)

It uses the => syntax and is often used for anonymous functions.

10/25/2025
Arrow functions
let add = (x,y) => return x+y; // no need for braces if only one statement

let sum = add(2,3)


Console.log(sum)
let myFunction=(a,b)=>a * b;
let mul=myFunction(2,3);
console.log(mul)

//similar to lambda functions in some other programming


languages, ...
// improves readability
// good for simple one-line actions

10/25/2025
Functions with parameters
• function message(name)
{ console.log(“Welcome”+name);}

message(“XYZ”);

• function message(name)
{ return(“Welcome”+name)}

Msg = message(“XYZ”);
console.log(Msg)
10/25/2025
Objects with functions
• const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + "
" + this.lastName;
}
};

• // can use getter or setter like


python
10/25/2025
Object and constructor
• Use a function to construct an object
• function car(make, model, year) {
this.make = make;
this.model = model;
this.year = year; } - cannot add more properties
• Objects with “prototype” helps to add more properties.
• var c = new car(“Ford”,”Taurus”,1988);
• car.prototype.print = function () {
return this.year + “ “ + this.make + “ “ + this.model;}
• c.print();

slide 84
.

Then what are classes in


Javascript?
• You can also use the class syntax instead of
the function syntax to define a constructor
function
• JavaScript Classes are templates for JavaScript
Objects.

class ClassName {
constructor() { ... } // add attributes

method_1() { ... }
method_2() { ... }
method_3() { ... }
}
10/25/2025
example
object Class
class Person {
constructor(name, age) {
let person = { this.name = name;
this.age = age;
name: 'John',
}
age: 30,
sayHello: function() { sayHello() {
console.log(`Hello, my name is $
console.log('Hello, my {this.name} and I'm ${this.age} years old.`);
name is ' + this.name + I’m }
+ this.age + ); }
} const john = new Person('John', 30);
john.sayHello();
};
10/25/2025
• Objects can also be created using the
Object.create() method. This method can
be very useful, because it allows you to
choose the prototype object for the
object you want to create, without having
to define a constructor function.

10/25/2025
Classes Vs Objects in JS
• Use a class when:
1.You need to create multiple objects with the same structure
and behavior.
2.You want to use inheritance to create a class hierarchy and
reuse code.
3.You want to use polymorphism to treat objects of different
classes as if they were the same type.
4.You want to encapsulate data and behavior in a single unit.
• Use an object when:
1.You need a single entity with specific state and behavior.
2.You don’t need to create multiple objects with the same
structure and behavior.
3.You don’t need to use inheritance or polymorphism.
4.You want a simple way to store and manipulate data.

10/25/2025
Try it

•Define a class named Account with a constructor that initializes properties such as accountNumber, accountHolder, and balance.
•Include methods within the class:
•displayAccountInfo: Display the account details (account number, account holder, balance).
•deposit: Accept an amount and add it to the account balance.
•withdraw: Accept an amount and subtract it from the account balance, ensuring sufficient funds.

• Create two instances of the Account class, representing different bank accounts.
• Call the displayAccountInfo method for each account to show their initial details.
• Perform a deposit operation on one account and a withdrawal operation on the others
• Call the displayAccountInfo method again for each account to show their updated details.

Your JavaScript program should demonstrate the use of classes, objects, and functions to model a basic banking system. Make
sure to handle scenarios where there might be insufficient funds during a withdrawal.

10/25/2025
Javascript in webpages

10/25/2025
Web page request

10/25/2025
Client Side Validation
• Done when the user input is validated by the
browser before it is sent to the server,
• Using HTML attributes, JavaScript, or other
scripting languages.
• Advantages
• provides instant feedback to the user
without reloading the page,
• reducing server load and bandwidth, and
• improving the user interface and usability.
• Drawbacks-
• bypassed by disabling or manipulating the browser
settings or scripts,
• being inconsistent across different browsers,
devices, and platforms, and being complex and
time-consuming to implement and maintain.
10/25/2025
Server Side Validation
• Is when the user input is validated by the server after it is
received from the browser, using languages such as PHP or
ASP.
• Provides a more reliable and secure validation, as it
can prevent malicious or invalid data from entering
the database or affecting the server functionality.
• Provides a more consistent and compatible validation,
as it can handle different browsers, devices, and
platforms, and apply the same rules and logic.
• provides a more flexible and dynamic validation, as it
can access the database or other resources, and
perform more complex or conditional validations.
• However, server-side validation can also cause a delay or lag
in the user feedback, increase the server load and
bandwidth, and degrade the user interface and usability.

10/25/2025
When and where to use
• Combining client-side and server-side validation is
the best practice for form validation, as it provides a
balance between the advantages and disadvantages of
each technique.
• Generally, client-side validation should be used for basic
and simple validations, such as required fields, format,
and range,
• while server-side validation should be used for advanced
and complex validations, such as uniqueness, existence,
and logic.
• Additionally, client-side validation can provide immediate
and interactive feedback to the user, and improve the
user experience and interface, while server-side
validation can provide final and authoritative validation,
and ensure data integrity and security.
• By following these guidelines, you can create a more
effective and efficient form validation for your data entry
10/25/2025
tasks.
Using JavaScript in html
document
• JavaScript code is included within <script> tags:
– <script type="text/javascript">
document.write("<h1>Hello World!</h1>") ;
</script>
• Notes:
• The type attribute is to allow you to use other
scripting languages (but JavaScript is the default)
• This simple code does the same thing as just putting
<h1>Hello World!</h1> in the same place in the
HTML document
• The semicolon at the end of the JavaScript statement
is optional
• You need semicolons if you put two or more statements
on the same line
• It’s probably a good idea to keep using semicolons
Where to put JavaScript
• JavaScript can be put in the <head> or in the <body>
of an HTML document
• JavaScript functions should be defined in the <head>
• This ensures that the function is loaded before it is
needed
• JavaScript in the <body> will be executed as the page
loads
• JavaScript can be put in a separate .js file
– <script src="myJavaScriptFile.js"></script>
• Put this HTML wherever you would put the actual
JavaScript code
• An external .js file lets you use the same JavaScript on
multiple HTML pages
• The external .js file cannot itself contain a <script> tag
• JavaScript can be put in HTML form object, such
How to set up client side validation

On the client side, validation can be done


in two ways:
1.Using HTML5 functionality
2.Using JavaScript

10/25/2025
Using HTML for client-side
validation
• Making fields required using “required”
• Constraining the length of data:
• minlength, maxlength: for text data
• min and max for the min and max value of num type
• Restricting the type of data using type:
• <input type="email" name="multiple>
• Specifying data patterns using pattern:
• specifies a regex pattern that the entered form data
needs to match

10/25/2025
HTML- validation
<form>
<label for="firstname"> First Name: </label>
<input type="text" name="firstname" id="firstname" required
maxlength="45">
<label for="lastname"> Last Name: </label>
<input type="text" name="lastname" id="lastname" required
maxlength="45">
<button>Submit</button>
</form>

10/25/2025
Using Regexp for
validation
• A regular expression (regexp) is a pattern
that can be used to match character
combinations in text strings, so regexps are
ideal for form validation and serve a variety
of other uses in JavaScript.

10/25/2025
A simple example using reg expr
<html lang="en">
<head>

<title>Simple example of JS in html</title>


<script>
function welcome(name)
{alert("welcome "+name);}
</script>
</head>
<body>
<form name="f1"
onsubmit="welcome(document.getElementById('fname').value)">
<label for="fname"> Name:</label>
<input type= "text" id = fname pattern="[A-Z] [a-z]+” title="start
with caps" required/>
CLICK the button for a welcome message
<input type="submit">
</form>
</body>
</html>>
10/25/2025
Popup boxes
alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
JS

CS380 103
An example for validation
using javascript
function validateUsername() {
var username = document.getElementById("username").value;
var usernameError = document.getElementById("usernameError");
if (username.trim() === "") {
usernameError.textContent = "Username cannot be empty.";
}
else {
for (var i = 0; i < username.length; i++)
{ var char = username[i];
if (!((char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || (char >=
'0' && char <= '9’)))
{ usernameError.textContent = "Invalid character in the username. Use
only letters and numbers."; return;
}
}
10/25/2025
Javascript Assignment 5.1, 5.2, 5.3 – Check the ppt for clear details
• Modify the JS welcome() function to check fname to have the first letter as a Capital letter followed by small case letters(No numbers or
other characters)followed by a space and capital letter and then small case letters
• Use .js file to write the welcome function.
• Try the same with pattern matching in html
• You are going to create an input form using HTML5 and Javascript. This input form will not submit any database to the server (you learn to
do this in COP4834). It will validate and collect information from the user and go to a confirm page that displays the information entered
and allows the user to confirm that the information is correct. Below are all the input form fields and the validation required.
• It is up to you (the designer) how you present the information request. For example in entering a date you can have a single text box, or you
can have multiple boxes with drop down choices. You do, however, have to validate the data to make sure it meets all validation rules.
• Once the user enters all this information in the form and hits submit, you will present the information and allow the user to confirm that it is
all correct. The user should not be able to enter invalid data or leave fields blank.
• The form will be sent to your email address using the form action=”mailto:address”

• Add a password field and Add a password strength bar to check the strength of your password.
• strong password : includes atleast 1 lowercase alphabet, atleast 1 uppercase alphabet, atleast one digit, atleast 1 special
character except dot and atleast 8 characters long. And not the username itself.
• medium password: same as above but no digits and can be atleast 6 characters long
• Weak password: If the password entered does not meet the strong or medium-level requirements,
then it is deemed weak.

10/25/2025
Assignment 5.2
• You are going to create an input form using HTML5 and Javascript. This input form will not submit any database to the server (you learn to
do this in COP4834). It will validate and collect information from the user and go to a confirm page that displays the information entered
and allows the user to confirm that the information is correct. Below are all the input form fields and the validation required.
• It is up to you (the designer) how you present the information request. For example in entering a date you can have a single text box, or you
can have multiple boxes with drop down choices. You do, however, have to validate the data to make sure it meets all validation rules.
• Once the user enters all this information in the form and hits submit, you will present the information and allow the user to confirm that it is
all correct. The user should not be able to enter invalid data or leave fields blank.
• The form will be sent to your email address using the form action=”mailto:address ”

10/25/2025
Assignment 5.2 --contd
(Use Javascript function)
• Add a password field and Add a password strength bar
to check the strength of your password.
• strong password : includes atleast 1 lowercase alphabet,
atleast 1 uppercase alphabet, atleast one digit, atleast 1
special character except dot and atleast 8 characters
long. And not the username itself.
• medium password: same as above but no digits and can
be atleast 6 characters long
• Weak password: If the password entered does
not meet the strong or medium-level
requirements, then it is deemed weak.
10/25/2025
How does Javascript
understand HTML document ?
• When an HTML document is loaded in the browser
– another representation of the same document is
generated as shown:
• Htmldoc JS view – DOM tree

10/25/2025
• HTML cannot be manipulated directly.
• It can be done using DOM with the help of Javascript
• The HTML DOM is a standard object model
and programming interface for HTML.
It defines:
• The HTML elements as objects
• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements
• In other words: The HTML DOM is a standard for how to get,
change, add, or delete HTML elements.

10/25/2025
DOM
Manipulations

• Javascript see DOM


as nodes
• Element Node
for e.g. head
• Attribute Node
for e.g. id
• Text Node for
e.g. My title

10/25/2025
Navigation between the
nodes
•nodeValue- innerHTML
•nodeName-
•parentNode
•childNodes[nodenumber]
•firstChild – childNodes[0]
•lastChild
•nextSibling
•previousSibling
Eg.
document.getElementById(“p1").firstChild.nodeValue;
document.getElementById(“p1").firstChild.nodeName;

10/25/2025
Javascript for dynamic
html
• JavaScript can change all the HTML elements in the page
• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and
attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the
page
• JavaScript can create new HTML events in the page

10/25/2025
Methods for manipulations
document object represents the web page.
• Finding HTML Element by Id
• const element=document.getElementById(“id1")
• Finding HTML Element by Tag Name
• const element=document.getElementsByTagName("p");
• Finding HTML Elements by Class Name
• const x=document.getElementsByClassName("intro");
• Finding HTML Elements by CSS Selectors
• const x = document.querySelectorAll("p.intro");
• returns a list of all <p> elements with class="intro

10/25/2025
Changing attributes…

Property Description
element.innerHTML = new html Change the inner HTML of an
content element
element.attribute = new value Change the attribute value of an
HTML element
element.style.property = new style Change the style of an HTML
element
Method Description
element.setAttribute(attribute, value) Change the attribute value of an
HTML element

10/25/2025
Element Manipulation

document.createElement(element) Create an HTML element

document.removeChild(element) Remove an HTML element

document.appendChild(element) Add an HTML element

document.replaceChild(new, old) Replace an HTML element

document.write(text) Write into the HTML output stream

10/25/2025
Finding HTML Objects

• document.anchors
• document.body
• document.documentElement
• document.embeds
• document.forms
• document.head
• document.images
• document.links
• document.scripts
• document.title
10/25/2025
Simple example
<html lang="en">
<head>
<title>Simple example of JS in
html</title>
</head> Change the text
<body> to “Welcome”
using JS
( dynamically)
<p id="sample">HELLO WORLD!!!
</p>
</body>
</html>

10/25/2025
Modify the example
<html lang="en">
<head>
<title>Simple example of JS in html</title>
</head> Display the
<body> URL of the
<script> document

document.getElementById("sample").innerHTML="WEL
COME !!!";
</script>
<p id="sample">HELLO WORLD!!! </p>
</body>
</html>
10/25/2025
Contd..

<body>
<p id="sample">HELLO WORLD!!! </p>
<script>
document.getElementById("sample").innerH
TML=document.URL;
</script>
</body>

10/25/2025
Assignment 5.3
• Identify the different ways of displaying the scripts
available in the document and show in the next page
of the document.
• Identify the number of HTML elements in the web
document
• Identify the number of each type of HTML element
in the document

10/25/2025
DOM Events

• When a user clicks the mouse – onclick,


onmousedown, onmouseup, onmouseover,
• When a web page has loaded - onload
• When an image has been loaded - onload
• When the mouse moves over an element-
onmouseover
• When an input field is changed – onchange,
onfocus
• When an HTML form is submitted- onsubmit
• When a user strokes a key – onkeydown,
onkeypress, onkeyup
10/25/2025
10/25/2025
10/25/2025
<!DOCTYPE html>
<html lang="en">
<head>

<title>Simple example of JS in html</title>


<script>
function welcome(name)
{alert("welcome "+name);}
</script>
</head>
<body>

<form name="f1"
onsubmit="welcome(document.getElementById('fname').value)">
<label for="fname"> Name:</label>
<input type= "text" id = fname pattern="[A-Za-z]+" title="start
with caps" required/>

CLICK the button for a welcome message


<input type="submit">
</form>
</body>
</html>
10/25/2025
JavaScript is not Java
• By now you should have realized that you already know a
great deal of JavaScript
• So far we have talked about things that are the same as in Java
• JavaScript has some features that resemble features in Java:
• JavaScript has Objects and primitive data types
• JavaScript has qualified names; for example,
document.write("Hello World");
• JavaScript has Events and event handlers
• Exception handling in JavaScript is almost the same as
in Java
• JavaScript has some features unlike anything in
Java:
• Variable names are untyped: the type of a variable
depends on the value it is currently holding
• Objects and arrays are defined in quite a different way
• JavaScript has with statements and a new kind of for
Warnings
• JavaScript is a big, complex language
• It’s easy to get started in JavaScript, but if you need to
use it heavily, plan to invest time in learning it well
• Write and test your programs a little bit at a time
• JavaScript is not totally platform independent
• Expect different browsers to behave differently
• Write and test your programs a little bit at a time
• Browsers aren’t designed to report errors
• Don’t expect to get any helpful error messages
• Write and test your programs a little bit at a time
Assignment 5.4
• Build a Simple To-Do List Application
using HTML, CSS, JS
• HTML
• Create an HTML file with appropriate
structure.
• Include input fields for adding new tasks, a
button to add tasks, and a list to display
tasks.
• CSS
• Style your To-Do List using CSS to make it
visually appealing.
10/25/2025
Do one by one
• JS
• Implement the following functionality using
JavaScript:Add tasks to the list when the user enters a
task description, due date and clicks the "Add" button.
• Display a validation message if the user tries to add an
empty task.
• Mark tasks as completed/uncompleted by clicking on
them.
• Delete tasks from the list.
• Provide a button to clear all completed tasks.
• Allow filtering tasks by "All," "Active," and "Completed"
categories.
• Order the tasks according to the due date.
• Change the background with an image if all tasks are
Completed
10/25/2025

You might also like