Secure Web Design and Development
Topic 5: Web Development - JavaScript
Instructor : Al Maha Abu Zuraiq
Cyber Security Department, Princess Sumaya University for Technology
Amman, Jordan
Web Development - JavaScript
What is JavaScript?
• JavaScript is a scripting language used to create interactive websites.
• JavaScript is a client-side scripting language that runs entirely inside the
web browser.
• JavaScript can change the content or the style of an element.
• It can calculate, manipulate and validate data and send a request to a
server.
Content Style Behavior
December 8, 2025 Web Development - JavaScript 2
Web Development - JavaScript
How to Insert JavaScript?
We can insert JavaScript into an HTML page in three ways:
• Inline JavaScript: Inside an HTML tag.
<button onclick="alert('Hello!')">Click Me</button>
• Internal JavaScript: Inside a <script> tag in the HTML file.
<script>
alert("Hello World!");
</script>
• External JavaScript: Using a separate .js file.
<script src="[Link]"></script>
December 8, 2025 Web Development - JavaScript 3
Web Development - JavaScript
When JavaScript is Run?
JavaScript runs in the browser when:
• Page Load: JavaScript runs when the page or specific elements are loaded.
o If the script element is inside the <head>, script will run before <body> is
loaded.
o If the script element is inside the <body> , script is will run as <body> is being
loaded.
• Event-Based: JavaScript runs in response to user actions (clicks, form
submissions, etc.).
• Timer-Based: JavaScript runs after a set delay (setTimeout(), setInterval()).
• Asynchronous: JavaScript runs to fetch data without reloading the page (AJAX).
December 8, 2025 Web Development - JavaScript 4
Web Development - JavaScript
General Information
• JavaScript is case sensitive.
• JavaScript generally doesn't require semicolons for single statements per
line, but when placing multiple statements on one line, semicolons are
necessary to separate them.
December 8, 2025 Web Development - JavaScript 5
Web Development - JavaScript
Comments
• Single-line comment:
// This is a single-line comment
• Multi-line comment:
/* This is
a multi-line comment */
December 8, 2025 Web Development - JavaScript 6
Web Development - JavaScript
Variables
Variables store data that can be used later in the program.
1. Var :
• Can be updated: You can change the value of a variable declared with var
after it's been initialized.
• Can be re-declared: You can declare a variable with var multiple times in
the same scope without causing an error.
• Scope: It has function scope or global scope if declared outside a
function, which can lead to unexpected behavior in some cases.
Ex:
var x = 10;
x = 20; // Updated
var x = 30; // Re-declared without an error
December 8, 2025 Web Development - JavaScript 7
Web Development - JavaScript
Variables
2. let:
• Can be updated: You can reassign a value to a variable declared with let.
• Cannot be re-declared in the same scope: If you try to declare the same
variable again with let in the same scope, it will throw an error.
• Scope: It has block scope, meaning it’s only accessible within the block
(e.g., inside a loop or if statement) where it’s declared.
EX:
let y = 10;
y = 20; // Updated
// let y = 30; // Error: Cannot redeclare 'y'
December 8, 2025 Web Development - JavaScript 8
Web Development - JavaScript
Variables
3. const:
• Cannot be updated: You cannot reassign a value to a variable declared
with const once it’s initialized.
• Cannot be re-declared in the same scope: Like let, you cannot redeclare
a const variable in the same scope.
• Scope: It also has block scope like let.
Ex:
const z = 10;
// z = 20; // Error: Assignment to constant variable
December 8, 2025 Web Development - JavaScript 9
Web Development - JavaScript
Data Types
• String: Text data.
let name = "John";
• Number: Integer or decimal.
let age = 30;
• Boolean: True or false.
let isStudent = true;
• Null: A deliberate assignment of "no value.“
let b = null;
• NaN (Not-a-Number): A result of an invalid number operation.
let result = a / 0; //(division by zero is not allowed, so result= NaN).
• Undefined: A variable that has been declared but not yet assigned a value.
let name; (default value in undefined)
December 8, 2025 Web Development - JavaScript 10
Web Development - JavaScript
Data Types
JavaScript is type-less, means that you don't need to declare the type of a
variable, it figures out the type based on value, and the type can be
changed.
<script>
Let x; // x is undefined
x = 2; // x is number
x = `Hi'; // x is now string
x = true; // x is now Boolean
x=null; // x is object
</script>
December 8, 2025 Web Development - JavaScript 11
Web Development - JavaScript
Arithmetic Operators
Operator Description Example
+ Addition J + 12
- Subtraction J - 12
* Multiplication J*7
/ Division J / 2.1
% Modulus (division remainder) J%6
++ Increment ++ J
-- Decrement -- J
December 8, 2025 Web Development - JavaScript 12
Web Development - JavaScript
Assignment Operators
Operator Example Equivalent to
= j = 99 j = 99
+= j += 2 j=j+2
j += ‘string’ j = j + ‘string’
-= j -= 12 j = j - 12
*= j *= 2 j=j*2
/= j /= 6 j=j/6
%= j %= 7 j=j%7
December 8, 2025 Web Development - JavaScript 13
Web Development - JavaScript
Comparison Operators
Operator Description Example
== Is equal to J == 2
!= Is not equal to J != 17
> Is greater than J>0
< Is less than J < 100
>= Is greater than or equal J >= 55
<= Is less than or equal J <= 30
=== Is equal to (and the J === 56
same type)
!== Is not equal in value or J !== ‘1’
type or both.
December 8, 2025 Web Development - JavaScript 14
Web Development - JavaScript
Logical Operators
Operator Example Example
&& And J == 1 && K == 2
|| Or J < 100 || J > 0
! Not ! ( J == K )
December 8, 2025 Web Development - JavaScript 15
Web Development - JavaScript
String Concatenation
In JavaScript, string concatenation is the process of joining two or more
strings together to form a single string.
The most basic way to concatenate strings is by using the + operator.
Ex:
let firstName = "John";
let lastName = "Doe";
// Concatenating the strings
let fullName = firstName + " " + lastName; // "John Doe"
December 8, 2025 Web Development - JavaScript 16
Web Development - JavaScript
Implicit Type Conversion
In JavaScript, implicit type conversion (also called type coercion) refers to JavaScript
automatically converting one data type to another when performing operations.
• Number + String → String When adding a number to a string, the number is
converted to a string and concatenated.
let number = 5;
let str = "10";
let result = number + str;// Output: "510"
• Number - String → Number When subtracting a string from a number, JavaScript
tries to convert the string into a number.
let number = 10;
let str = "5";
let str1 =“ hello”
let result = number - str; // Output: 5
let result = number – str1; // Output: NaN
December 8, 2025 Web Development - JavaScript 17
Web Development - JavaScript
Implicit Type Conversion
• String * Number → Number When multiplying a string by a number, JavaScript
converts the string to a number and performs the multiplication. (same as
subtraction)
• String / Number → Number When dividing a string by a number, JavaScript
converts the string to a number and performs the division. (same as subtraction).
• Boolean + Number → Number true is converted to 1, and false is converted to 0
when added to a number.
• Boolean + String → String true is converted to "true", and false to "false" when
added to a string.
• Null + Number → Number null is converted to 0 when added to a number.
• Null + String → String null is converted to "null" when added to a string.
• Undefined + Anything → NaN Adding undefined to any other value results in NaN
(Not-a-Number).
• String == Number → Comparison When comparing a string with a number using
==, JavaScript tries to convert the string into a number before comparison.
December 8, 2025 Web Development - JavaScript 18
Web Development - JavaScript
Escape Characters
• Escape characters are used to represent special characters that cannot be typed
directly into a string, or to allow certain characters to be treated as literal
characters.
Esc Sequence Character Description
\' ' Single quote
\" " Double quote
\\ \ Backslash
\n Newline (\n) Line break (moves to the next line)
\t Tab Horizontal tab
\b Backspace Removes the previous character
\uXXXX Unicode (4 digits) Unicode character (e.g., \u0041 for "A")
Unicode (5-6 digits,
\u{XXXXX} Unicode character (e.g., \u{1F600} for 😊)
ES6+)
December 8, 2025 Web Development - JavaScript 19
Web Development - JavaScript
Output
In JavaScript, output refers to displaying or logging information to the console, on the
web page, or in some other medium.
1. Console Output:
• [Link](): This method prints the output to the browser's console.
• [Link](): This outputs an error message to the console.
• [Link](): This outputs a warning message to the console.
• [Link](): This method is used to display data in a tabular format.
December 8, 2025 Web Development - JavaScript 20
Web Development - JavaScript
Output
2. Displaying Output on a Web Page:
a) Using [Link]() to write directly to the HTML document. It is not
recommended for modern web development because it can overwrite the entire
document if used improperly.
December 8, 2025 Web Development - JavaScript 21
Web Development - JavaScript
Output
• [Link]() Example:
December 8, 2025 Web Development - JavaScript 22
Web Development - JavaScript
Output
2. Displaying Output on a Web Page:
b) Modifying HTML Elements: You can dynamically modify the content of HTML
elements using JavaScript.
o The .value property is used to Get or Set the value of form elements.
o The .innerHTML property is used to get or set the content inside HTML
elements (including HTML tags).
December 8, 2025 Web Development - JavaScript 23
Web Development - JavaScript
Output
• The alert() is used to display an alert box with a message and an OK button,
the user must click OK to close the box and continue.
• The open() is used to opens a new browser window or tab with a specified
URL. Ex:
<script>
function openNewWindow() {
[Link]("[Link] "_blank)
}
</script>
December 8, 2025 Web Development - JavaScript 24
Web Development - JavaScript
Input
• HTML Form Inputs: You can get input from various HTML form elements (e.g.,
text fields, checkboxes, radio buttons, etc.). Ex:
• [Link]("name").value;
• Using prompt() function to displays a dialog box with a text input field and returns
the value entered by the user.
December 8, 2025 Web Development - JavaScript 25
Web Development - JavaScript
Input
• The confirm() method is used to display a confirmation dialog box. It asks the
user a yes/no question and returns a Boolean value based on the user's response.
o true if the user clicked OK (Yes).
o false if the user clicked Cancel (No).
December 8, 2025 Web Development - JavaScript 26
Web Development - JavaScript
If Statement
• The if statement is used to execute a block of code if the condition is true.
• Syntax:
if (condition) {
// code to be executed if condition is true
}
• Example:
December 8, 2025 Web Development - JavaScript 27
Web Development - JavaScript
Else if Statement
• The else if statement allows you to execute one block of code if the condition is
true, and another block if it's false.
• Syntax:
if (condition1) {
// code if condition if condition1 is true
} else if(condition 2){
// code if condition is condition2 is true
}
else
{
// code if condition if both conditions are false
}
December 8, 2025 Web Development - JavaScript 28
Web Development - JavaScript
Switch Statement
• The switch statement is used to perform different actions based on different
conditions.
• Syntax: • Example:
switch (expression) {
case value1:
// code if expression == value1
break;
case value2:
// code if expression == value2
break;
default:
// code if no match
}
December 8, 2025 Web Development - JavaScript 29
Web Development - JavaScript
The ? Operator (Ternary Operator)
• The ternary operator is a shorthand for the if-else statement.
• Syntax:
condition ? expression_if_true : expression_if_false;
• Example:
December 8, 2025 Web Development - JavaScript 30
Web Development - JavaScript
While Loop
• A while loop repeats a block of code as long as the specified condition is true.
• Syntax:
while (condition) {
// code to be executed
}
• Example:
December 8, 2025 Web Development - JavaScript 31
Web Development - JavaScript
Do-While Loop
• A do-while loop always executes the block of code at least once, then continues as
long as the condition is true.
• While runs as long as the condition is true, while do-while ensures the code inside
runs at least once.
• Syntax:
do {
// code to be executed
} while (condition);
• Example:
December 8, 2025 Web Development - JavaScript 32
Web Development - JavaScript
For Loop
• A for loop repeats a block of code a specified number of times.
• Syntax:
for (initialization; condition; increment) {
// code to be executed
}
• Example:
for(let i=0 ; i < 5 ; i++){
[Link](i);
}
December 8, 2025 Web Development - JavaScript 33
Web Development - JavaScript
Break Statement
• The break statement is used to exit a loop or a switch statement early.
• Syntax:
break;
• Example:
December 8, 2025 Web Development - JavaScript 34
Web Development - JavaScript
Continue Statement
• The continue statement is used to to skip the rest of the current iteration and move
on to the next one.
• Syntax:
continue;
• Example:
for (let i = 1; i <= 10; i++) {
if (i %2 != 0) {
continue; // Skip number 5
}
[Link]("Number:", i);
}
December 8, 2025 Web Development - JavaScript 35
Web Development - JavaScript
Function
• A function is a block of code designed to perform a particular task. Functions are
reusable.
• If a value is returned, then use the keyword return.
• Syntax:
function functionName(parameter) {
// code to be executed
}
functionName(Argument);
• Examples:
December 8, 2025 Web Development - JavaScript 36
Web Development - JavaScript
Variable Scope
• Variable scope refers to the accessibility of variables. Variables can have global or
local scope:
o Global: accessible wherever in the code.
o Local: only accessible inside the function where it declared.
• Example:
December 8, 2025 Web Development - JavaScript 37
Web Development - JavaScript
Try...Catch Statement
• The try...catch statement is used to handle exceptions (errors) in JavaScript. When
an error happened we will not reach the end of the program because JS is
interpreted language.
Error examples:
• Syntax Errors: Misspelled keywords or variable names.
• Runtime Errors: ReferenceError: When you refer to a variable or function that is
not defined. TypeError: This appears when you try to perform an unauthorized
operation on the current data type.
• Logical Errors: incorrect if statement condition.
• Syntax:
try {
// code that may throw an error
} catch (error) {
// code to handle the error
}
December 8, 2025 Web Development - JavaScript 38
Web Development - JavaScript
Try...Catch Statement
• Examples:
December 8, 2025 Web Development - JavaScript 39
Web Development - JavaScript
Throw Statement
• The throw statement is used to manually create an exception (error) in
JavaScript.
• When you want to signal an error in your program, you can use throw with
a custom error message or object.
• This is useful for enforcing conditions and handling errors explicitly.
• Syntax:
throw expression;
• Example:
December 8, 2025 Web Development - JavaScript 40
Web Development - JavaScript
Array in JavaScript
• An array is a special variable that can hold more than one value at a time.
• Arrays are used to store multiple values in a single variable.
• A 1D array is an array with a single level, meaning it contains a list of values
indexed by numbers, this is the most basic form of an array.
• Syntax:
let array_name = [value1, value2, value3];
• Example:
• What if I want to display it in a table format?
December 8, 2025 Web Development - JavaScript 41
Web Development - JavaScript
Element Indexing in Arrays
• Indexing in arrays refers to accessing individual elements using their
position (index).
• JavaScript arrays are zero-indexed, meaning the first element has an
index of 0, the second element has an index of 1, and so on..
• Accessing an index outside the array's bounds will return undefined.
• Example:
December 8, 2025 Web Development - JavaScript 42
Web Development - JavaScript
Changing or Adding to an Array
• You can change an array element using its index or adding a new
element.
• Basic Example:
December 8, 2025 Web Development - JavaScript 43
Web Development - JavaScript
Array Methods
• pop(): Removes the last element from an array.
• push(): Adds one or more elements to the end of an array.
• shift(): Removes the first element of an array.
• unshift(): Adds one or more elements to the beginning of an array.
• Example:
December 8, 2025 Web Development - JavaScript 44
Web Development - JavaScript
Array Methods
• toString(): Converts an array to a string, separating elements with
commas.
• join(): Joins array elements into a string, with a custom separator.
• concat(): Combines two or more arrays into one new array.
• Example:
December 8, 2025 Web Development - JavaScript 45
Web Development - JavaScript
Array Methods
• slice(): Extracts a portion of an array and returns a new array without
modifying the original array.
• length: Returns the number of elements in an array.
• delete: Removes an element from an array but doesn't change the array's
length.
• Example:
December 8, 2025 Web Development - JavaScript 46
Web Development - JavaScript
Other Array Methods
• forEach(): Executes a provided function once for each array element.
• sort(): Sorts the elements of an array.
• reverese():Reverses the order of the elements in an array.
• Example:
December 8, 2025 Web Development - JavaScript 47
Web Development - JavaScript
Strings in JavaScript
• A string is a sequence of characters used to represent text.
• Strings are enclosed in single (‘ ') or double (" ") quotes.
• Strings are immutable — you can’t change characters directly.
• Example:
December 8, 2025 Web Development - JavaScript 48
Web Development - JavaScript
String Methods
• .length : Returns the number of characters in a string.
• .charAt(index): Returns the character at a specified index (starts from 0).
• .indexOf(searchValue): Returns the index of the first occurrence of the
specified value and returns -1 if not found.
• .toUpperCase(): Converts all characters to uppercase.
• .toLowerCase(): Converts all characters to lowercase.
• Example:
December 8, 2025 Web Development - JavaScript 49
Web Development - JavaScript
String Methods
• .slice(start, end): Extracts a part of a string and returns it as a new string and does
not change the original string.
• .replace(old, new): Replaces the first match of a substring with a new string, the
original string remains unchanged.
• .replaceAll(old, new): Replaces every occurrence of a substring with a new
substring and returns a new string.
• .split(separator): Splits a string into an array based on a separator.
• Example:
December 8, 2025 Web Development - JavaScript 50
Web Development - JavaScript
Date Object in JavaScript
JavaScript has a built-in Date object for working with dates and times.
Syntax:
new Date();
Example:
December 8, 2025 Web Development - JavaScript 51
Web Development - JavaScript
Date methods
• .toLocaleString(): Converts the Date object into a readable string format
(based on locale settings).
• .getFullYear(): Returns the 4-digit year from a Date object.
• .getMonth(): Returns the month (0-11) from the Date (0 = January, 11 =
December).
• .getDate(): Returns the day of the month (1-31).
• .getDay(): Returns the day of the week (0-6), (0 = Sunday, 6 = Saturday).
• .getHours(): Current hour (24-hour format).
• .getMinutes(): Current minutes.
• .getSeconds(): Current seconds.
Web Development - JavaScript 52
December 8, 2025
Web Development - JavaScript
Date methods
• Example:
December 8, 2025 Web Development - JavaScript 53
Web Development - JavaScript
[Link] Object
• The [Link] object contains information about the current URL.
• You can also use it to redirect the user to a different page.
o [Link]: To get or set full URL.
o [Link]: To get domain name
o [Link]: To get path (e.g., /[Link])
o [Link]: To get protocol (http:, https:)
o [Link]("[Link] : To redirect when script is
loaded.
o What about [Link](“[Link]
December 8, 2025 Web Development - JavaScript 54
Web Development - JavaScript
[Link] Object
• Example:
December 8, 2025 Web Development - JavaScript 55
Web Development - JavaScript
[Link] Object
• The [Link] object allows navigation back and forward through the
browser's history.
• [Link](); : To go to previous page.
• [Link](); : To go to next page.
• [Link](-1); : To go back one page.
• [Link](1); : To go forward one page.
December 8, 2025 Web Development - JavaScript 56
Web Development - JavaScript
[Link] Object
• Example:
December 8, 2025 Web Development - JavaScript 57
Web Development - JavaScript
[Link] Object
Examples:
• Custom Back Button:
Ex: <button onclick="[Link]()">Go Back</button>
• Refresh Page:
Ex: [Link](0); // Reloads current page
What if I want to refresh the page automatically every 10 seconds?
<script>
setInterval(function(){
[Link]();
}, 10000);
</script>
December 8, 2025 Web Development - JavaScript 58
Web Development - JavaScript
Document Object Model (DOM)
• The DOM represents the structure of an HTML document as a tree of
objects.
• JavaScript can access and modify HTML via the DOM.
December 8, 2025 Web Development - JavaScript 59
Web Development - JavaScript
Accessing HTML Elements in JavaScript
• [Link]("id"):
Selects one element by its ID.
• [Link]("class"):
Selects all elements with the given class name.
• [Link]("tag"):
Selects all elements with the given tag name (e.g., "p", "div").
December 8, 2025 Web Development - JavaScript 60
Web Development - JavaScript
Accessing HTML Elements in JavaScript
December 8, 2025 Web Development - JavaScript 61
Web Development - JavaScript
Changing HTML Content
• .innerHTML: for normal HTML elements (like <p>, <div>, etc.)
• .value: for form input elements (like <input>, <textarea>)
• Example:
December 8, 2025 Web Development - JavaScript 62
Web Development - JavaScript
Changing CSS Style of Elements
• .style: Change CSS style.
• .className: Change CSS Class of Element.
• Example:
December 8, 2025 Web Development - JavaScript 63
Web Development - JavaScript
Accessing and Changing Attributes
• .getAttribute: To get attribute value.
• .setAttribute: To change attribute value.
• Example:
December 8, 2025 Web Development - JavaScript 64
Web Development - JavaScript
Accessing Document Information
• [Link]: Returns the title of the page.
• [Link]: Returns the full URL of the document (read-only).
• [Link]: Returns the last updated date/time of the
document.
• [Link]: Returns the current page’s cookies as a string.
December 8, 2025 Web Development - JavaScript 65
Web Development - JavaScript
Accessing HTML Elements with document
Built-in Element References:
• [Link]: Returns the <head> element of the page.
• [Link]: Returns the <body> element of the page.
• [Link]: Returns a collection of all <img> elements.
• [Link]: Returns all <form> elements in the document.
December 8, 2025 Web Development - JavaScript 66
Web Development - JavaScript
Accessing Form Properties
Accessing Form Details by Index
[0] means the first form in the document :
• [Link]: Returns a list of the document forms.
• [Link][0].id: Returns the ID of the form.
• [Link][0].name: Returns the Name of the form.
• [Link][0].method: Returns the Submission method (GET or
POST).
• [Link][0].action: Returns the Submission URL.
• [Link][0].elements[i].id: Returns the ID of an input inside the
form.
December 8, 2025 Web Development - JavaScript 67
Web Development - JavaScript
Accessing Form Properties (Example)
December 8, 2025 Web Development - JavaScript 68
Web Development - JavaScript
Nested Access in the DOM
• Accessing an Element Inside Another Element:
• Nested access in forms
December 8, 2025 Web Development - JavaScript 69
Web Development - JavaScript
Adding and Removing Elements
• .createElement(): Creates a new HTML element.
• .appendChild(): Adds a child element to a parent at the end.
• .removeChild(): Removes a specified child from a parent.
• .insertBefore(): Inserts a new element before a specific child.
• .replaceChild(): Replaces an existing child with a new one.
December 8, 2025 Web Development - JavaScript 70
Web Development - JavaScript
Adding and Removing Elements (Example)
December 8, 2025 Web Development - JavaScript 71
Web Development - JavaScript
JavaScript Events
An event is an action that occurs in the browser, such as: Click, hover, key
press, form submit, page load, etc.
Common JavaScript Events:
• onclick: When the mouse clicks an element.
• onerror: When a document or image fails to load.
• onload: When a page or image finishes loading.
• onsubmit: When a form is submitted.
• oninput: When the user enters input (real-time).
• onchange: When the value of an input changes (after focus lost).
• onmouseover: When the mouse pointer hovers over an element.
December 8, 2025 Web Development - JavaScript 72
Web Development - JavaScript
JavaScript Events
Keyboard Events
• onkeydown: When a key is pressed on the keyboard.
• onkeyup: When the a key is released.
The [Link] or [Link] properties can be used to determine which key pressed.
For example:
o [Link]: "Enter", "a", "ArrowLeft", etc.
o [Link]: "Enter", "KeyA", "ArrowLeft", etc.
Mouse Events
• onmousedown: When a mouse button is pressed down.
• onmouseup: When the mouse button is released.
The [Link] property can be used to determine which mouse button pressed:
o 0: Left mouse button
o 1: Middle mouse button (typically the scroll wheel button)
o 2: Right mouse button
December 8, 2025 Web Development - JavaScript 73
Web Development - JavaScript
Applying Events Handlers
• Applying Event Handlers (Direct Method)
You can attach an event directly using an HTML attribute:
<button onclick="alert('Button clicked!')">Click Me</button>
• Adding Event Listeners (JS Method)
Adds a click event listener using JS (cleaner & more flexible).
<button id="btn">Click</button>
<script>
[Link]("btn").addEventListener("click", function () {
[Link]("Button clicked using addEventListener");
});
</script>
December 8, 2025 Web Development - JavaScript 74
Web Development - JavaScript
Applying Events Handlers
• Removing Event Listeners
<button id="infoBtn">Hover me</button>
<script>
function showTip() {
alert("This is your first tip!");
[Link]("mouseover", showTip);
}
const infoBtn = [Link]("infoBtn");
[Link]("mouseover", showTip);
</script>
December 8, 2025 Web Development - JavaScript 75
Web Development - JavaScript
Forms Validation
• JavaScript and HTML5 provide mechanisms for form validation, but each
has its strengths, and using JavaScript in combination with HTML5
validation can provide a more robust solution.
• Advantage of HTML5
• Simplicity
• Advantage of JavaScript
• Customized and Complex Validation
December 8, 2025 Web Development - JavaScript 76
Web Development - JavaScript
Forms Validation
<form id="registerForm" action="[Link]"
onsubmit="return validateForm()">
Name: <input type="text" id="name" ><br/>
<input type="submit" value="register">
</form>
<script>
function validateForm(){
var name=[Link]("name").value;
if (name==null || name==""){
alert("Name can't be blank"); return false;
}
else return true;
} </script>
December 8, 2025 Web Development - JavaScript 77
Web Development - JavaScript
Regular Expression - Brackets [ ]
• [abcde]: Any one character between the brackets
• [^abcde]: Any one character not between the brackets
• [0-9]: Any digit between 0 and 9
• [a-z]: Any one lowercase character
• [A-Z]: Any one uppercase character
December 8, 2025 Web Development - HTML Forms 78
Web Development - JavaScript
Regular Expression - Quantifier
• +: One or more
• *: Zero or more
• ?: At most one
• N: Exactly N
• N,M: Between N and M inclusive
• N,: Greater than or equal to N
• ,M: Less then or equal to M
December 8, 2025 Web Development - HTML Forms 79
Web Development - JavaScript
Regular Expression - Metacharacters
• $: The end of the string
• ^: The beginning of the string
• .: A single character
December 8, 2025 Web Development - HTML Forms 80
Web Development - JavaScript
Regular Expression Example
let regex = /^[a-z]+$/
[Link]([Link]('hello')); // true
[Link]([Link]('HELLO’)); // false
[Link]([Link]('hello123’)); // false
[Link]([Link]('abc!')); // false
December 8, 2025 Web Development - HTML Forms 81
Web Development – JavaScript
What is jQuery?
• jQuery doesn't give you complete "scripts" like templates or plug-and-play features
(unless you use plugins), but it gives you ready-to-use, simplified methods to write
JavaScript more efficiently.
• A fast, lightweight JavaScript library.
• Makes it easier to: Select and modify HTML elements.
• Handle events like clicks and keypresses.
• Create animations.
• Syntax is short and easy to use.
• Latest version is 3.7.1.
jQuery Download Options:
• Option 1: CDN
<script src="[Link]
• Option 2: Download
Visit [Link] download the .js file and link it in your project.
December 8, 2025 Web Development – Bootstrap and jQuery 82
Web Development – JavaScript
jQuery Syntax
Syntax:
$(selector).action()
Selector Examples:
• Element Selector: $("p")
• The id selector: $("#test")
• The class selector: $(".test")
Action Examples:
• click
• dblclick
• keypress
December 8, 2025 Web Development – Bootstrap and jQuery 83
Web Development – JavaScript
jQuery Example
Examples:
• $("p").css("background-color", "yellow");
• $("img").attr("width","500");
• $("#element").attr("class", "new-class");
• $("#myButton").click(function() {
alert("Button was clicked!");
}
December 8, 2025 Web Development – Bootstrap and jQuery 84
Web Development – JavaScript
jQuery Example
Using jQuery Without jQuery
<button id="btn">Click Me</button> <button id="btn">Click Me</button>
<p id="text">Hello</p> <p id="text">Hello</p>
<script <script>
src="[Link]
[Link]"></script> [Link]("DOMContentLo
aded", function() {
<script> var btn = [Link]("btn");
$("#btn").click(function() { var text = [Link]("text");
$("#text").text("You clicked the
button!"); [Link]("click", function() {
}); [Link] = "You clicked the
</script> button!";
});
});
</script>
December 8, 2025 Web Development – Bootstrap and jQuery 85