0% found this document useful (0 votes)
31 views

Web Technology Unit 3 Part 1

The document provides an introduction to JavaScript including its uses, advantages, limitations and syntax. It discusses JavaScript variables, scope, reserved words, operators, conditional statements and if/else blocks. Key points covered include JavaScript is used to create interactive web pages, it has client-side scripting capabilities, and conditionally executes code using if/else statements.

Uploaded by

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

Web Technology Unit 3 Part 1

The document provides an introduction to JavaScript including its uses, advantages, limitations and syntax. It discusses JavaScript variables, scope, reserved words, operators, conditional statements and if/else blocks. Key points covered include JavaScript is used to create interactive web pages, it has client-side scripting capabilities, and conditionally executes code using if/else statements.

Uploaded by

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

UNIT II

Java Script

An introduction to JavaScript:
Java script is language developed strictly for the web sites to create interactive web page that can
handle calculations, controls such as displaying certain information when certain values provided,
validate forms, and more without whole lot of programming effort. In short description, java script
is easy programming language specifically designed to make web page elements interactive. An
interactive element is one that responds to a user’s input. Java Script is case sensitive.
Advantages of JavaScript
The merits of using JavaScript are −
 Less server interaction − You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
 Immediate feedback to the visitors − They don't have to wait for a page reload to see if
they have forgotten to enter something.
 Increased interactivity − You can create interfaces that react when the user hovers over
them with a mouse or activates them via the keyboard.
 Richer interfaces − You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.

Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the following
important features −
 Client-side JavaScript does not allow the reading or writing of files. This has been kept for
security reason.
 JavaScript cannot be used for networking applications because there is no such support
available.
 JavaScript doesn't have any multithreading or multiprocessor capabilities.

Java script syntax:


JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script>.
You can place the <script> tags, containing your JavaScript, anywhere within your web page, but
it is normally recommended that you should keep it within the <head> tags.
The script tag takes two important attributes –

 Language − This attribute specifies what scripting language you are using. Typically, its
value will be javascript. Although recent versions of HTML (and XHTML, its successor)
have phased out the use of this attribute.
 Type − This attribute is what is now recommended to indicate the scripting language in use
and its value should be set to "text/javascript".
So your JavaScript segment will look like −

<script language="javascript" type="text/javascript">


JavaScript code

</script>
Case Sensitivity
JavaScript is a case-sensitive language. This means that the language keywords, variables, function
names, and any other identifiers must always be typed with a consistent capitalization of letters.
Comments in JavaScript
JavaScript supports both C-style and C++-style comments, Thus −
 Any text between a // and the end of a line is treated as a comment and is ignored by
JavaScript.
 Any text between the characters /* and */ is treated as a comment. This may span multiple
lines.
 JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats
this as a single-line comment, just as it does the // comment.
 The HTML comment closing sequence --> is not recognized by JavaScript so it should be
written as //-->.
Example:
<html>
<body>
<script language="javascript" type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>

 Javascript can be used in both head and body sections.


JavaScript Variables
Variables are declared with the var keyword as follows.
<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>
JavaScript Variable Scope
The scope of a variable is the region of your program in which it is defined. JavaScript variables
have only two scopes.
 Global Variables − A global variable has global scope which means it can be defined
anywhere in your JavaScript code.
 Local Variables − A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the
same name. If you declare a local variable or function parameter with the same name as a global
variable, you effectively hide the global variable. Take a look into the following example.
<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
</body>
</html>
JavaScript Reserved Words
A list of all the reserved words in JavaScript are given in the following table. They cannot be used
as JavaScript variables, functions, methods, loop labels, or any object names.
abstract else instanceof switch

boolean enum int synchronized

break export interface this

byte extends long throw

case false native throws

catch final new transient

char finally null true

class float package try

const for private typeof

continue function protected var

debugger goto public void

default if return volatile

delete implements short while

do import static with

double in super

JavaScript Operators
JavaScript supports the following types of operators.
 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
Arithmetic Operators
+,-,*,/,%,++,--
Example
The following code shows how to use arithmetic operators in JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);
a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);
b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->
</script>
Set the variables to different values and then try...
</body>
</html>
Output
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
++a = 35
--b = 8
Set the variables to different values and then try...
Comparison Operators
==,!=,<,<=,>,>=
Logical Operators
JavaScript supports the following logical operators −
&&,||,!
Bitwise Operators
JavaScript supports the following bitwise operators −
 & (Bitwise AND)
 | (BitWise OR)
 ^ (Bitwise XOR)
 ~ (Bitwise Not)
 << (Left Shift)
 >> (Right Shift)
 >>> (Right shift with Zero)
This operator is just like the >> operator, except that the bits shifted in on the left are always zero.
Ex: (A >>> 1) is 1.
Assignment Operators
 = (Simple Assignment )
 += (Add and Assignment)
 −= (Subtract and Assignment)
 *= (Multiply and Assignment)
 /= (Divide and Assignment)
 %= (Modules and Assignment)
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then executes
one of the two given statements depending upon the result of the evaluation.

JavaScript - if...else Statement

JavaScript supports conditional statements which are used to perform different actions based on
different conditions.
JavaScript supports the following forms of if..else statement −
 if statement
 if...else statement
 if...else if... statement.
if statement
The if statement is the fundamental control statement that allows JavaScript to make decisions and
execute statements conditionally.
Syntax
The syntax for a basic if statement is as follows −
if (expression){
Statement(s) to be executed if expression is true
}
Example
Try the following example to understand how the if statement works.
<html>
<body>
<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Qualifies for driving
Set the variable to different value and then try...
if...else statement:
The 'if...else' statement is the next form of control statement that allows JavaScript to execute
statements in a more controlled way.
Syntax
if (expression){
Statement(s) to be executed if expression is true
}
else{
Statement(s) to be executed if expression is false
}
if...else if... statement
The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct
decision out of several conditions.
Syntax
The syntax of an if-else-if statement is as follows −
if (expression 1){
Statement(s) to be executed if expression 1 is true
}
else if (expression 2){
Statement(s) to be executed if expression 2 is true
}
else if (expression 3){
Statement(s) to be executed if expression 3 is true
}
else{
Statement(s) to be executed if no expression is true
}

JavaScript - Switch Case

Syntax
The objective of a switch statement is to give an expression to evaluate and several different
statements to execute based on the value of the expression. The interpreter checks
each case against the value of the expression until a match is found. If nothing matches,
a default condition will be used.
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...

case condition n: statement(s)


break;
default: statement(s)
}
The break statements indicate the end of a particular case. If they were omitted, the interpreter
would continue executing each statement in each of the following cases.
We will explain break statement in Loop Control chapter.
Example
Try the following example to implement switch-case statement.
<html>
<body>
<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
case 'A': document.write("Good job<br />");
break;
case 'B': document.write("Pretty good<br />");
break;
case 'C': document.write("Passed<br />");
break;
case 'D': document.write("Not so good<br />");
break;

case 'F': document.write("Failed<br />");


break;
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>
Output
Entering switch block
Good job
Exiting switch block
Set the variable to different value and then try...

JavaScript - While Loops

Syntax
The syntax of while loop in JavaScript is as follows −
while (expression){
Statement(s) to be executed if expression is true
}
Example
Try the following example to implement while loop.
<html>
<body>
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop ");
while (count < 10){
document.write("Current Count : " + count + "<br />");
count++;
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Syntax
The syntax for do-while loop in JavaScript is as follows −

do{

Statement(s) to be executed;

} while (expression);
Note − Don‘t miss the semicolon used at the end of the do...while loop.

JavaScript - For Loop

Syntax
The syntax of for loop is JavaScript is as follows −
for (initialization; test condition; iteration statement){
Statement(s) to be executed if test condition is true
}
Example
Try the following example to learn how a for loop works in JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++){
document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

JavaScript for...in loop

The for...in loop is used to loop through an object's properties.


Syntax
for (variablename in object){
statement or block to execute
}
In each iteration, one property from object is assigned to variablename and this loop continues till
all the properties of the object are exhausted.
Example
Try the following example to implement ‗for-in‘ loop. It prints the web
browser‘s Navigator object.
<html>
<body>

<script type="text/javascript">
<!--
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator) {
document.write(aProperty);
document.write("<br />");
}
document.write ("Exiting from the loop!");
//-->
</script>
<p>Set the variable to different object and then try...</p>
</body>
</html>

JavaScript – Functions

A function is a group of reusable code which can be called anywhere in your program. This
eliminates the need of writing the same code again and again. It helps programmers in writing
modular codes. Functions allow a programmer to divide a big program into a number of small and
manageable functions.
Syntax
The basic syntax is shown here.
<script type="text/javascript">
<!--
function functionname(parameter-list)
{
statements
}
//-->
</script>
Example
Try the following example. It defines a function called sayHello that takes no parameters −
<script type="text/javascript">
<!--
function sayHello()
{
alert("Hello there");
}
//-->
</script>
Calling a Function
To invoke a function somewhere later in the script, you would simply need to write the name of
that function as shown in the following code.
<html>
<head>
<script type="text/javascript">
function sayHello()
{
document.write ("Hello there!");
}
</script>

</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>
Function Parameters
These passed parameters can be captured inside the function and any manipulation can be done
over those parameters. A function can take multiple parameters separated by comma.
Example
Try the following example. We have modified our sayHello function here. Now it takes two
parameters.
<html>
<head>
<script type="text/javascript">
function sayHello(name, age)
{
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello('Zara', 7)" value="Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>

2. JavaScript DOM Model


The HTML DOM (Document Object Model)

When a web page is loaded, the browser creates a Document Object Model of the page.

The HTML DOM model is constructed as a tree of Objects:


The HTML DOM Tree of Objects

With the object model, JavaScript gets all the power it needs to create 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

JavaScript - HTML DOM Methods

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.
In the DOM, all HTML elements are defined as objects.
The programming interface is the properties and methods of each object.
A property is a value that you can get or set (like changing the content of an HTML element).
A method is an action you can do (like add or deleting an HTML element).
Example
The following example changes the content (the innerHTML) of the <p> element with id="demo":
Example
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>

JavaScript HTML DOM Document

The HTML DOM document object is the owner of all other objects in your web page.
The HTML DOM Document Object
The document object represents your web page.
If you want to access any element in an HTML page, you always start with accessing the document
object.
Below are some examples of how you can use the document object to access and manipulate
HTML.
Finding HTML Elements
Method Description

document.getElementById(id) Find an element by element id

document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(name) Find elements by class name

JavaScript HTML DOM Elements

This page teaches you how to find and access HTML elements in an HTML page.
Finding HTML Elements
Often, with JavaScript, you want to manipulate HTML elements.
To do so, you have to find the elements first. There are a couple of ways to do this:
 Finding HTML elements by id
 Finding HTML elements by tag name
 Finding HTML elements by class name
Finding HTML Element by Id
The easiest way to find an HTML element in the DOM, is by using the element id.
example
<!DOCTYPE html>
<html>
<body>
<p id="intro">Hello World!</p>
<p>This example demonstrates the <b>getElementById</b> method!</p>
<p id="demo"></p>
<script>
var myElement = document.getElementById("intro");
document.getElementById("demo").innerHTML =
"The text from the intro paragraph is " + myElement.innerHTML;
</script>
</body>
</html>
Finding HTML Elements by Tag Name
This example finds all <p> elements:
Example
 var x = document.getElementsByTagName("p");
Finding HTML Elements by Class Name
If you want to find all HTML elements with the same class name, use getElementsByClassName().
This example returns a list of all elements with class="intro".
Example
 var x = document.getElementsByClassName("intro");

JavaScript HTML DOM Events

HTML DOM allows JavaScript to react to HTML events:

Reacting to Events
A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.
To execute code when a user clicks on an element, add JavaScript code to an HTML event
attribute:

onclick=JavaScript
Examples of HTML events:
 When a user clicks the mouse
 When a web page has loaded
 When an image has been loaded
 When the mouse moves over an element
 When an input field is changed
 When an HTML form is submitted
 When a user strokes a key
3. Date and Objects
Date methods let you get and set date values (years, months, days, hours, minutes, seconds,
milliseconds)
Date Get Methods

Get methods are used for getting a part of a date. Here are the most common (alphabetically):
Method Description

getDate() Get the day as a number (1-31)

getDay() Get the weekday as a number (0-6)

getFullYear() Get the four digit year (yyyy)


getHours() Get the hour (0-23)

getMilliseconds() Get the milliseconds (0-999)

getMinutes() Get the minutes (0-59)

getMonth() Get the month (0-11)

getSeconds() Get the seconds (0-59)

getTime() Get the time (milliseconds since January 1, 1970)

The getTime() Method

getTime() returns the number of milliseconds since January 1, 1970:


example
<!DOCTYPE html>
<html>
<body>
<p>The internal clock in JavaScript starts at midnight January 1, 1970.</p>
<p>The getTime() function returns the number of milliseconds since then:</p>
<p id="demo"></p>
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getTime();
</script>
</body>
</html>
The getFullYear() Method

getFullYear() returns the year of a date as a four digit number:


Example
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getFullYear();
</script>
The getDay() Method

getDay() returns the weekday as a number (0-6):


Example
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getDay();
</script>
Date Set Methods

Set methods are used for setting a part of a date. Here are the most common (alphabetically):
Method Description

setDate() Set the day as a number (1-31)

setFullYear() Set the year (optionally month and day)

setHours() Set the hour (0-23)

setMilliseconds() Set the milliseconds (0-999)

setMinutes() Set the minutes (0-59)

setMonth() Set the month (0-11)

setSeconds() Set the seconds (0-59)

setTime() Set the time (milliseconds since January 1, 1970)

The setFullYear() Method


setFullYear() sets a date object to a specific date. In this example, to January 14, 2020:
Example
<script>
var d = new Date();
d.setFullYear(2020, 0, 14);
document.getElementById("demo").innerHTML = d;
</script>
Compare Dates
Dates can easily be compared.

The following example compares today's date with January 14, 2100:
Example
var today, someday, text;
today = new Date();
someday = new Date();
someday.setFullYear(2100, 0, 14);

if (someday > today) {


text = "Today is before January 14, 2100.";
} else {
text = "Today is after January 14, 2100.";
}
document.getElementById("demo").innerHTML = text;
4. Regular Expressions
A regular expression is an object that describes a pattern of characters.
Regular expressions are used to perform pattern-matching and "search-and-replace" functions on
text.
Syntax
/pattern/modifiers;
Modifiers

Modifiers are used to perform case-insensitive and global searches:


Modifier Description

i Perform case-insensitive matching

g Perform a global match (find all matches rather than stopping after the first match)

m Perform multiline matching

Brackets

Brackets are used to find a range of characters:


Expression Description

[abc] Find any character between the brackets

[^abc] Find any character NOT between the brackets

[0-9] Find any character between the brackets (any digit)

[^0-9] Find any character NOT between the brackets (any non-digit)

(x|y) Find any of the alternatives specified

Metacharacters

Metacharacters are characters with a special meaning:


Metacharacter Description

. Find a single character, except newline or line terminator

\w Find a word character

\W Find a non-word character

\d Find a digit

\D Find a non-digit character


\s Find a whitespace character

\S Find a non-whitespace character

\b Find a match at the beginning/end of a word

\B Find a match not at the beginning/end of a word

\0 Find a NUL character

\n Find a new line character

\f Find a form feed character

\r Find a carriage return character

\t Find a tab character

\v Find a vertical tab character

\xxx Find the character specified by an octal number xxx

\xdd Find the character specified by a hexadecimal number dd

\uxxxx Find the Unicode character specified by a hexadecimal number xxxx

Quantifiers
Quantifier Description

n+ Matches any string that contains at least one n

n* Matches any string that contains zero or more occurrences of n

n? Matches any string that contains zero or one occurrences of n

n{X} Matches any string that contains a sequence of X n's

n{X,Y} Matches any string that contains a sequence of X to Y n's

n{X,} Matches any string that contains a sequence of at least X n's

n$ Matches any string with n at the end of it

^n Matches any string with n at the beginning of it

?=n Matches any string that is followed by a specific string n

?!n Matches any string that is not followed by a specific string n


RegExp Object Properties
Property Description

constructor Returns the function that created the RegExp object's prototype

global Checks whether the "g" modifier is set

ignoreCase Checks whether the "i" modifier is set

lastIndex Specifies the index at which to start the next match

multiline Checks whether the "m" modifier is set

source Returns the text of the RegExp pattern


RegExp Object Methods
Method Description

compile() Deprecated in version 1.5. Compiles a regular expression

exec() Tests for a match in a string. Returns the first match

test() Tests for a match in a string. Returns true or false

toString() Returns the string value of the regular expression

5. Exception Handling
JavaScript Errors - Throw and Try to Catch
 The try statement lets you test a block of code for errors.
 The catch statement lets you handle the error.
 The throw statement lets you create custom errors.
 The finally statement lets you execute code, after try and catch, regardless of the result.
When executing JavaScript code, different errors can occur. Errors can be coding errors made by
the programmer, errors due to wrong input, and other unforeseeable things.
Example:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
try {
adddlert("Welcome guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>
</body>
</html>
JavaScript try and catch
The try statement allows you to define a block of code to be tested for errors while it is being
executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the
try block.
The JavaScript statements try and catch come in pairs:
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
JavaScript Throws Errors
When an error occurs, JavaScript will normally stop and generate an error message.
The technical term for this is: JavaScript will throw an exception (throw an error).
Input Validation Example
This example examines input. If the value is wrong, an exception (err) is thrown.
The exception (err) is caught by the catch statement and a custom error message is displayed:
<!DOCTYPE html>
<html>
<body>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="message"></p>

<script>
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {
message.innerHTML = "Input is " + err;
}
}
</script>
</body>
</html>
The finally Statement
The finally statement lets you execute code, after try and catch, regardless of the result:
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of the try / catch result
}
Example:
<!DOCTYPE html>
<html>
<body>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="message"></p>
<script>
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "is empty";
if(isNaN(x)) throw "is not a number";
x = Number(x);
if(x > 10) throw "is too high";
if(x < 5) throw "is too low";
}
catch(err) {
message.innerHTML = "Input " + err;
}
finally {
document.getElementById("demo").value = "";
}
}
</script>
</body>
</html>
Error Name Values

Six different values can be returned by the error name property:

Error Name Description


EvalError An error has occurred in the eval() function

RangeError A number "out of range" has occurred

ReferenceError An illegal reference has occurred

SyntaxError A syntax error has occurred

TypeError A type error has occurred

URIError An error in encodeURI() has occurred

6. Validation
JavaScript Form Validation
HTML form validation can be done by JavaScript.
If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the
form from being submitted:
JavaScript Example

function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
HTML Form Example
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>

<form name="myForm" action="/action_page.php"


onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
Automatic HTML Form Validation
HTML form validation can be performed automatically by the browser:

<form action="/action_page.php" method="post">


<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>
If we press submit button browser will automatically generate error.
Data Validation
Data validation is the process of ensuring that user input is clean, correct, and useful.
Typical validation tasks are:
 has the user filled in all required fields?
 has the user entered a valid date?
 has the user entered text in a numeric field?
Most often, the purpose of data validation is to ensure correct user input.
Validation can be defined by many different methods, and deployed in many different ways.
Server side validation is performed by a web server, after input has been sent to the server.
Client side validation is performed by a web browser, before input is sent to a web server.
HTML Constraint Validation
HTML5 introduced a new HTML validation concept called constraint validation.
HTML constraint validation is based on:
 Constraint validation HTML Input Attributes
 Constraint validation CSS Pseudo Selectors
 Constraint validation DOM Properties and Methods

Constraint Validation HTML Input Attributes

Attribute Description

disabled Specifies that the input element should be disabled

max Specifies the maximum value of an input element

min Specifies the minimum value of an input element

pattern Specifies the value pattern of an input element

required Specifies that the input field requires an element

type Specifies the type of an input element

7. Built-in objects in javascript

In JavaScript, almost "everything" is an object.

 Booleans can be objects (if defined with the new keyword)


 Numbers can be objects (if defined with the new keyword)
 Strings can be objects (if defined with the new keyword)
 Dates are always objects
 Maths are always objects
 Regular expressions are always objects
 Arrays are always objects
 Functions are always objects
 Objects are always objects

All JavaScript values, except primitives, are objects.

JavaScript defines 5 types of primitive data types:


 string
 number
 boolean
 null
 undefined
 if x = 3.14, you can change the value of x. But you cannot change the value of 3.14. 

Value Type Comment

"Hello" string "Hello" is always "Hello"

3.14 number 3.14 is always 3.14

true boolean true is always true

false boolean false is always false

null null (object) null is always null

undefined undefined undefined is always undefined

Object Methods
Methods are actions that can be performed on objects.
Object properties can be both primitive values, other objects, and functions.
An object method is an object property containing a function definition.
Property Value

firstName John

lastName Doe

age 50

eyeColor blue

fullName function() {return this.firstName + " " + this.lastName;}


JavaScript objects are containers for named values, called properties and methods.
Creating a JavaScript Object
With JavaScript, you can define and create your own objects.
There are different ways to create new objects:
 Define and create a single object, using an object literal.
 Define and create a single object, with the keyword new.
 Define an object constructor, and then create objects of the constructed type.
Using an Object Literal

 This is the easiest way to create a JavaScript Object.


 Using an object literal, you both define and create an object in one statement.
 An object literal is a list of name:value pairs (like age:50) inside curly braces {}.
 The following example creates a new JavaScript object with four properties

<!DOCTYPE html>
<html>
<body>
<p>Creating a JavaScript Object.</p>
<p id="demo"></p>
<script>
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>
</body>
</html>
Using the JavaScript Keyword new
The following example also creates a new JavaScript object with four properties:
Example:

<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>
</body>
</html>
JavaScript Properties
Properties are the values associated with a JavaScript object.
A JavaScript object is a collection of unordered properties.
Properties can usually be changed, added, and deleted, but some are read only.
Accessing JavaScript Properties
The syntax for accessing the property of an object is:
objectName.property // person.age
or
objectName["property"] // person["age"]
or
objectName[expression] // x = "age"; person[x]
Example:
<!DOCTYPE html>
<html>
<body>

<p>There are two different ways to access an object property:</p>


<p>You can use .property or ["property"].</p>

<p id="demo"></p>

<script>
var person = {
firstname:"John",
lastname:"Doe",
age:50,
eyecolor:"blue"
};
document.getElementById("demo").innerHTML =
person.firstname + " is " + person.age + " years old.";
</script>

</body>
</html>
Adding New Properties
You can add new properties to an existing object by simply giving it a value.
Assume that the person object already exists - you can then give it new properties:
Example
person.nationality = "English";
Deleting Properties
The delete keyword deletes a property from an object:
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
delete person.age; // or delete person["age"];
The delete keyword deletes both the value of the property and the property itself. After deletion, the
property cannot be used before it is added back again.
Property Attributes
All properties have a name. In addition they also have a value.
The value is one of the property's attributes. Other attributes are: enumerable, onfigurable, and
writable. These attributes define how the property can be accessed .
In JavaScript, all attributes can be read, but only the value attribute can be changed (and only if the
property is writable).
The this Keyword
In JavaScript, the thing called this, is the object that "owns" the JavaScript code.
The value of this, when used in a function, is the object that "owns" the function.
Note that this is not a variable. It is a keyword. You cannot change the value of this.
Accessing Object Methods
You access an object method with the following syntax:
objectName.methodName()
You will typically describe fullName() as a method of the person object, and fullName as a
property.
The fullName property will execute (as a function) when it is invoked with ().
This example accesses the fullName() method of a person object:
<!DOCTYPE html>
<html>
<body>

<p>Creating and using an object method.</p>

<p>A method is actually a function definition stored as a property value.</p>

<p id="demo"></p>

<script>
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

document.getElementById("demo").innerHTML = person.fullName();
</script>
</body>
</html>
Using Built-In Methods
This example uses the toUpperCase() method of the String object, to convert a text to uppercase:
var message = "Hello world!";
var x = message.toUpperCase();
The value of x, after execution of the code above will be:
HELLO WORLD!
Using an Object Constructor
The examples from the previous chapters are limited in many situations. They only create single
objects.
Sometimes we like to have an "object type" that can be used to create many objects of one type.
The standard way to create an "object type" is to use an object constructor function:
<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}

var myFather = new Person("John", "Doe", 50, "blue");


var myMother = new Person("Sally", "Rally", 48, "green");

document.getElementById("demo").innerHTML =
"My father is " + myFather.age + ". My mother is " + myMother.age;
</script>

</body>
</html>
Built-in JavaScript Constructors
JavaScript has built-in constructors for native objects:
<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var x1 = new Object(); // A new Object object
var x2 = new String(); // A new String object
var x3 = new Number(); // A new Number object
var x4 = new Boolean(); // A new Boolean object
var x5 = new Array(); // A new Array object
var x6 = new RegExp(); // A new RegExp object
var x7 = new Function(); // A new Function object
var x8 = new Date(); // A new Date object

document.getElementById("demo").innerHTML =
"x1: " + typeof x1 + "<br>" +
"x2: " + typeof x2 + "<br>" +
"x3: " + typeof x3 + "<br>" +
"x4: " + typeof x4 + "<br>" +
"x5: " + typeof x5 + "<br>" +
"x6: " + typeof x6 + "<br>" +
"x7: " + typeof x7 + "<br>" +
"x8: " + typeof x8 + "<br>";
</script>
<p>There is no need to use String(), Number(), Boolean(), Array(), and RegExp()</p>
<p>Read the JavaScript tutorials.</p>

</body>
</html>
Output:
x1: object
x2: object
x3: object
x4: object
x5: object
x6: object
x7: function
x8: object
There is no need to use String(), Number(), Boolean(), Array(), and RegExp()
Read the JavaScript tutorials.
String Objects
Normally, strings are created as primitives: var firstName = "John"
But strings can also be created as objects using the new keyword: var firstName = new
String("John")
Learn why strings should not be created as object in the chapter JS Strings.

Number Objects
Normally, numbers are created as primitives: var x = 123
But numbers can also be created as objects using the new keyword: var x = new Number(123)
Learn why numbers should not be created as object in the chapter JS Numbers.

Boolean Objects
Normally, booleans are created as primitives: var x = false
But booleans can also be created as objects using the new keyword: var x = new Boolean(false)
Learn why booleans should not be created as object in the chapter JS Booleans.
8. Event Handling

JavaScript - Events

JavaScript's interaction with HTML is handled through events that occur when the user or the
browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is an event.
Other examples include events like pressing any key, closing a window, resizing a window, etc.
onclick Event Type
This is the most frequently used event type which occurs when a user clicks the left button of his
mouse. You can put your validation, warning etc., against this event type.
Example
Try the following example.
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello" />
</form>
</body>
</html>
onsubmit Event type
onsubmit is an event that occurs when you try to submit a form. You can put your form validation
against this event type.
onmouseover and onmouseout
These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and
the onmouseout triggers when you move your mouse out from that element. Try the following
example.
<html>
<head>
<script type="text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>

<div onmouseover="over()" onmouseout="out()">


<h2> This is inside the division </h2>
</div>
</body>
</html>
HTML 5 Standard Events
The standard HTML 5 events are listed here for your reference. Here script indicates a Javascript
function to be executed against that event.
Attribute Value Description

Offline script Triggers when the document goes offline

Onabort script Triggers on an abort event

onafterprint script Triggers after the document is printed

onbeforeonload script Triggers before the document loads

onbeforeprint script Triggers before the document is printed

onblur script Triggers when the window loses focus

Triggers when media can start play, but might has to stop for
oncanplay script
buffering

Triggers when media can be played to the end, without stopping for
oncanplaythrough script
buffering

onchange script Triggers when an element changes

onclick script Triggers on a mouse click

oncontextmenu script Triggers when a context menu is triggered

ondblclick script Triggers on a mouse double-click

ondrag script Triggers when an element is dragged

ondragend script Triggers at the end of a drag operation

ondragenter script Triggers when an element has been dragged to a valid drop target

ondragleave script Triggers when an element is being dragged over a valid drop target

ondragover script Triggers at the start of a drag operation

ondragstart script Triggers at the start of a drag operation

ondrop script Triggers when dragged element is being dropped

ondurationchange script Triggers when the length of the media is changed

onemptied script Triggers when a media resource element suddenly becomes empty.

onended script Triggers when media has reach the end

onerror script Triggers when an error occur


onfocus script Triggers when the window gets focus

onformchange script Triggers when a form changes

onforminput script Triggers when a form gets user input

onhaschange script Triggers when the document has change

oninput script Triggers when an element gets user input

oninvalid script Triggers when an element is invalid

onkeydown script Triggers when a key is pressed

onkeypress script Triggers when a key is pressed and released

onkeyup script Triggers when a key is released

onload script Triggers when the document loads

onloadeddata script Triggers when media data is loaded

Triggers when the duration and other media data of a media element
onloadedmetadata script
is loaded

onloadstart script Triggers when the browser starts to load the media data

onmessage script Triggers when the message is triggered

onmousedown script Triggers when a mouse button is pressed

onmousemove script Triggers when the mouse pointer moves

onmouseout script Triggers when the mouse pointer moves out of an element

onmouseover script Triggers when the mouse pointer moves over an element

onmouseup script Triggers when a mouse button is released

onmousewheel script Triggers when the mouse wheel is being rotated

onoffline script Triggers when the document goes offline

onoine script Triggers when the document comes online

ononline script Triggers when the document comes online

onpagehide script Triggers when the window is hidden

onpageshow script Triggers when the window becomes visible

You might also like