JavaScript Tutorial
JavaScript is the world's most popular programming language. It is the
language for HTML, for the web, for servers, PCs, laptops, tablets, phones, and
more. You can write directly to HTML
<script>
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
</script>
You will often
see document.getElementById("some id"). This
is defined in the HTML DOM. The DOM (Document Object
Model) is the official W3C standard for accessing HTML
elements. You will find several chapters about the HTML DOM in this tutorial.
<!DOCTYPE html>
<body>
<h1>My First JavaScript</h1>
<p id="demo">JavaScript can change the content of an HTML
element.</p>
<script>
function myFunction()
{
x=document.getElementById("demo"); // Find the element
x.innerHTML="Hello JavaScript!"; // Change the content
}
</script>
<button type="button"
onclick="myFunction()">Click Me!</button>
</body></html>
<!DOCTYPE
html><html><head>
<script>
function
displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script></head>
<body>
<h1>My
First JavaScript</h1>
<p
id="demo">This is a paragraph.</p>
<button
type="button" onclick="displayDate()">Display
Date</button>
</body></html>
JavaScript: Changing HTML Images
<!DOCTYPE
html>
<body>
<script>
function
changeImage()
{
element=document.getElementById('myimage')
if
(element.src.match("bulbon"))
{
element.src="pic_bulboff.gif";
} else {
element.src="pic_bulbon.gif";
}
}
</script>
<img
id="myimage" onclick="changeImage()" src="pic_bulboff.gif"
width="100" height="180">
<p>Click
the light bulb to turn on/off the light</p></body></html>
To change
the color of Text
function
myfunction()
{
x=document.getElementById("demo")
x.style.color="red";
}
JavaScript Output
Manipulating HTML Elements
To access an
HTML element from JavaScript, you can use the document.getElementById(id)
method.
Use the
"id" attribute to identify the HTML element:
<!DOCTYPE
html><html><body>
<h1>My
First Web Page</h1>
<p
id="demo">My First Paragraph.</p>
<script>
document.getElementById("demo").innerHTML="My
First JavaScript";
</script></body></html>
Writing to The Document Output
The example
below writes a <p> element directly into the HTML document output:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<script>
document.write("<p>My First JavaScript</p>");
</script></body></html>
<html>
<body>
<h1>My First Web Page</h1>
<script>
document.write("<p>My First JavaScript</p>");
</script></body></html>
Warning
Use
document.write() only to write directly into the document output.
If you execute
document.write after the document has finished loading, the entire HTML page
will be overwritten:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
document.write("Oops! The document disappeared!");
}
</script>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
document.write("Oops! The document disappeared!");
}
</script>
</body></html>
JavaScript Statements
JavaScript
is a sequence of statements to be executed by the browser. JavaScript
statements are "commands" to the browser.
The purpose of
the statements is to tell the browser what to do.
This JavaScript
statement tells the browser to write "Hello Dolly" inside an HTML
element with id="demo":
document.getElementById("demo").innerHTML="Hello
Dolly";
You might see examples without semicolons.
Ending statements with semicolon is optional in JavaScript.
Ending statements with semicolon is optional in JavaScript.
JavaScript Code
JavaScript code
(or just JavaScript) is a sequence of JavaScript statements.Each statement is
executed by the browser in the sequence they are written. This example will
manipulate two HTML elements:
document.getElementById("demo").innerHTML="Hello
Dolly";
document.getElementById("myDIV").innerHTML="How are you?";
document.getElementById("myDIV").innerHTML="How are you?";
JavaScript Code Blocks
JavaScript statements can be
grouped together in blocks. Blocks start with a left curly bracket, and end
with a right curly bracket. The purpose of a block is to make the sequence of
statements execute together. A good
example of statements grouped together in blocks, are JavaScript functions.
function myFunction()
{
document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";
}
{
document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";
}
JavaScript is Case Sensitive
White Space
JavaScript
ignores extra spaces. You can add white space to your script to make it more
readable. The following lines are equivalent:
var
person="Hege";
var person = "Hege";
var person = "Hege";
Break up a Code Line
You can break up
a code line within a text string with a backslash. The example below
will be displayed properly:
document.write("Hello \
World!");
World!");
However, you
cannot break up a code line like this:
document.write \
("Hello World!");
("Hello World!");
JavaScript Comments
Single line comments start with //.
Multi line comments start with /* and end with */.
JavaScript Data Types
When you assign
a text value to a variable, put double or single quotes around the value.
When you assign
a numeric value to a variable, do not put quotes around the value. If you put
quotes around a numeric value, it will be treated as text.
var pi=3.14;
var person="John Doe";
var answer='Yes I am!';
var person="John Doe";
var answer='Yes I am!';
One Statement, Many Variables
You can declare
many variables in one statement. Just start the statement with var and
separate the variables by comma:
var lastname="Doe", age=30,
job="carpenter"; Your
declaration can also span multiple lines:
var lastname="Doe",
age=30,
job="carpenter";
age=30,
job="carpenter";
Re-Declaring JavaScript Variables
If you
re-declare a JavaScript variable, it will not lose its value:.
The value of the
variable carname will still have the value "Volvo"
after the execution of the following:
var carname="Volvo";
var carname;
var carname;
JavaScript Data Types
String, Number, Boolean, Array, Object, Null, Undefined. JavaScript Has Dynamic Types
JavaScript has
dynamic types. This means that the same variable can be used as different
types:
Example
var
x;
// Now x is undefined
var x = 5; // Now x is a Number
var x = "John"; // Now x is a String
var x = 5; // Now x is a Number
var x = "John"; // Now x is a String
JavaScript Arrays
The following
code creates an Array called cars:
var cars=new Array();
cars[0]="Saab";
cars[1]="Volvo";
cars[2]="BMW";
cars[0]="Saab";
cars[1]="Volvo";
cars[2]="BMW";
or (condensed
array):
var cars=new
Array("Saab","Volvo","BMW");
or (literal
array):
Example
var
cars=["Saab","Volvo","BMW"];
Array indexes are zero-based, which means the first
item is [0], second is [1], and so on.
JavaScript Objects
An object is
delimited by curly braces. Inside the braces the object's properties are
defined as name and value pairs (name : value). The properties are separated by
commas:
var person={firstname:"John",
lastname:"Doe", id:5566};
The object
(person) in the example above has 3 properties: firstname, lastname, and id.
Spaces and line
breaks are not important. Your declaration can span multiple lines:
var person={
firstname : "John",
lastname : "Doe",
id : 5566
};
firstname : "John",
lastname : "Doe",
id : 5566
};
You can address
the object properties in two ways:
name=person.lastname;
name=person["lastname"];
name=person["lastname"];
Declaring Variables as Objects
When a variable is declared with
the keyword "new", the variable is declared as an object:
var name = new String;
var x = new Number;
var y = new Boolean;
var x = new Number;
var y = new Boolean;
JavaScript Objects
Almost everything in
JavaScript can be an Object: Strings, Functions, Arrays, Dates....
Objects are just data,
with properties and methods.
Properties and Methods
Properties are values
associated with objects.
Methods are actions
that objects can perform.
The properties of
the car include name, model, weight, color, etc.
All cars have these properties, but
the property values differ from car to car.
The methods of the
car could be start(), drive(), brake(), etc.
All cars have these methods, but
they are performed at different times.
Objects in JavaScript:
In JavaScript,
objects are data (variables), with properties and methods.
You create a
JavaScript String object when you declare a string variable like this:
var txt = new String("Hello World");
String
objects have built-in properties and methods:
In object
oriented languages, properties and methods are often called object
members.
Creating JavaScript Objects
Almost "everything" in JavaScript can be objects. Strings, Dates, Arrays, Functions.... You can also create your own objects. This example creates an object called "person", and adds four properties to it:
person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
Accessing Object Properties
The syntax for
accessing the property of an object is:
objectName.propertyName
This example
uses the length property of the String object to find the length of a string:
var message="Hello World!";
var x=message.length;
var x=message.length;
The value of x,
after execution of the code above will be: 12.
Accessing Object Methods
You can call a
method with the following syntax:
objectName.methodName()
This example
uses the toUpperCase() method of the String object, to convert a text to
uppercase:
var message="Hello world!";
var x=message.toUpperCase();
var x=message.toUpperCase();
The value of x,
after execution of the code above will be:
HELLO WORLD!
JavaScript Function Syntax
A function is written as a code
block (inside curly { } braces), preceded by the function
keyword:
function functionname()
{
some code to be executed
}
{
some code to be executed
}
<!DOCTYPE
html>
<body>
<p>Click
the button to call a function with arguments</p>
<button
onclick="myFunction('Harry Potter','Wizard')">Try
it</button>
<script>
function
myFunction(name,job)
{
alert("Welcome
" + name + ", the " + job);
}
</script>
</body></html>
Functions With a Return Value
Sometimes you want your function to
return a value back to where the call was made.
This is possible by using the return
statement.
When using the return
statement, the function will stop executing, and return the specified value.
Syntax
function myFunction()
{
var x=5;
return x;
}
{
var x=5;
return x;
}
Local JavaScript Variables
A variable declared (using var)
within a JavaScript function becomes LOCAL and can only be accessed from
within that function. (the variable has local scope).
You can have local variables with
the same name in different functions, because local variables are only
recognized by the function in which they are declared.
Local variables are deleted as soon
as the function is completed.
Global JavaScript Variables
Variables
declared outside a function, become GLOBAL, and all scripts and functions
on the web page can access it.
The Lifetime of JavaScript Variables
The lifetime JavaScript variables
starts when they are declared.
Local variables are deleted when
the function is completed.
Global variables are deleted when
you close the page.
Assigning Values to Undeclared JavaScript Variables
If you assign a value to variable
that has not yet been declared, the variable will automatically be declared as
a GLOBAL variable.
This statement:
carname="Volvo";
JavaScript Operators
JavaScript Arithmetic Operators
Arithmetic
operators are used to perform arithmetic between variables and/or values. Given
that y=5, the table below explains the arithmetic operators:
Operator
|
Description
|
Example
|
Result
of x
|
Result
of y
|
+
|
Addition
|
x=y+2
|
7
|
5
|
-
|
Subtraction
|
x=y-2
|
3
|
5
|
*
|
Multiplication
|
x=y*2
|
10
|
5
|
/
|
Division
|
x=y/2
|
2.5
|
5
|
%
|
Modulus (division remainder)
|
x=y%2
|
1
|
5
|
++
|
Increment
|
x=++y
|
6
|
6
|
x=y++
|
5
|
6
|
||
--
|
Decrement
|
x=--y
|
4
|
4
|
x=y--
|
5
|
4
|
JavaScript Assignment Operators
Assignment
operators are used to assign values to JavaScript variables. Given that x=10
and y=5, the table below explains the assignment operators:
Operator
|
Example
|
Same
As
|
Result
|
=
|
x=y
|
x=5
|
|
+=
|
x+=y
|
x=x+y
|
x=15
|
-=
|
x-=y
|
x=x-y
|
x=5
|
*=
|
x*=y
|
x=x*y
|
x=50
|
/=
|
x/=y
|
x=x/y
|
x=2
|
%=
|
x%=y
|
x=x%y
|
x=0
|
The + Operator Used on Strings
The + operator
can also be used to add string variables or text values together.
Example
To
add two or more string variables together, use the + operator.
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
txt2="nice day";
txt3=txt1+txt2;
The result of txt3
will be:
What a verynice day
To add a space
between the two strings, insert a space into one of the strings:
Example
txt1="What a very ";
txt2="nice day";
txt3=txt1+txt2;
txt2="nice day";
txt3=txt1+txt2;
The result of txt3
will be:
What a very nice day
or insert a
space into the expression:
Example
txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;
txt2="nice day";
txt3=txt1+" "+txt2;
The result of txt3
will be:
What a very nice day
Adding Strings and Numbers
Adding two
numbers, will return the sum, but adding a number and a string will return a
string:
Example
x=5+5;
y="5"+5;
z="Hello"+5;
y="5"+5;
z="Hello"+5;
The result of x,y,
and z will be:
10
55
Hello5
55
Hello5
JavaScript Comparison and Logical Operators
Comparison
and Logical operators are used to test for true or false.
Comparison Operators
Comparison
operators are used in logical statements to determine equality or difference
between variables or values.
Given that x=5,
the table below explains the comparison operators:
Operator
|
Description
|
Comparing
|
Returns
|
==
|
equal to
|
x==8
|
false
|
x==5
|
true
|
||
===
|
exactly equal to (equal value and
equal type)
|
x==="5"
|
false
|
x===5
|
true
|
||
!=
|
not equal
|
x!=8
|
true
|
!==
|
not equal (different value or different type)
|
x!=="5"
|
true
|
x!==5
|
false
|
||
>
|
greater than
|
x>8
|
false
|
<
|
less than
|
x<8
|
true
|
>=
|
greater than or equal to
|
x>=8
|
false
|
<=
|
less than or equal to
|
x<=8
|
true
|
How Can it be Used
Comparison
operators can be used in conditional statements to compare values and take
action depending on the result:
if (age<18) x="Too young";
You will learn
more about the use of conditional statements in the next chapter of this
tutorial.
Logical Operators
Logical
operators are used to determine the logic between variables or values.
Given that x=6
and y=3, the table below explains the logical operators:
Operator
|
Description
|
Example
|
&&
|
and
|
(x < 10 && y > 1)
is true
|
||
|
or
|
(x==5 || y==5) is false
|
!
|
not
|
!(x==y) is true
|
Conditional Operator
JavaScript also
contains a conditional operator that assigns a value to a variable based on
some condition.
Syntax
variablename=(condition)?value1:value2
If
the variable age is a value below 18, the value of the variable voteable
will be "Too young, otherwise the value of voteable will be
"Old enough":
voteable=(age<18)?"Too
young":"Old enough";
Conditional Statements
In JavaScript we have the following
conditional statements:
- if statement - use this statement to execute some code only if a specified condition is true
- if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false
- if...else if....else statement - use this statement to select one of many blocks of code to be executed
- switch statement - use this statement to select one of many blocks of code to be executed
<head></head>
<body>
<p> Here small function for Welcome the user</p>
<p id="demo"></p>
<script>
function myday()
{
t=new Date().getHours();
if (t<12)
{
x = " Good Morning Dear User";
}
else if (t<17)
{
x = "Good Afternoon Dear User";
}
else if (t<24)
{
x= "Goodnight Dear User";
}
else
{
x= "I do not Know what to tell";
}
document.getElementById("demo").innerHTML=x;
}
document.getElementById("msg").innerHTML=myday();
</script>
<p id="msg"></p>
</body></html>
The JavaScript Switch Statement
Use the switch
statement to select one of many blocks of code to be executed.
Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
This is how it works: First we have a single
expression n (most often a variable), that is evaluated once. The value
of the expression is then compared with the values for each case in the
structure. If there is a match, the block of code associated with that case is
executed. Use break to prevent the code from running into the next case
automatically.
<!DOCTYPE html>
<head></head>
<body>
<p id="msg"></p>
<script>
function myswitch()
{
var x;
var n=new Date().getDay();
switch (n)
{
case 0:
x= "Today Sunday";
break;
case 1:
x="Today Monday";
break;
case 2:
x="Today Tuesday";
break;
case 3:
x="Today Wendensday";
break;
case 4:
x="Today Thursday";
break;
case 5:
x="Today Friday";
break;
case 6:
x="Today Saturday";
break;
default:
x=" so funy I do not know what is Today";
}
document.getElementById("msg").innerHTML=x;
}
document.getElementById("demo").innerHTML=myswitch();
</script>
<p id="demo"></p>
</body></html>
The default Keyword
Use the default
keyword to specify what to do if there is no match: If it is NOT Saturday or
Sunday, then write a default message:
JavaScript Loops
Loops are handy, if you want to run
the same code over and over again, each time with a different value.
Often this is the case when working
with arrays:
Instead of writing:
document.write(cars[0] + "<br>");
document.write(cars[1] + "<br>");
document.write(cars[2] + "<br>");
document.write(cars[3] + "<br>");
document.write(cars[4] + "<br>");
document.write(cars[5] + "<br>");
document.write(cars[1] + "<br>");
document.write(cars[2] + "<br>");
document.write(cars[3] + "<br>");
document.write(cars[4] + "<br>");
document.write(cars[5] + "<br>");
<!DOCTYPE html>
<html>
<body>
<script>
cars=["BMW","Volvo","Saab","Ford"];
for (var i=0;i<cars.length;i++)
{
document.write(cars[i] +
"<br>");
}
</script></body></html>
Different Kinds of Loops
JavaScript supports different kinds
of loops:
- for - loops through a block of code a number of times
- for/in - loops through the properties of an object
- while - loops through a block of code while a specified condition is true
- do/while - also loops through a block of code while a specified condition is true
The For Loop
The for loop is
often the tool you will use when you want to create a loop.
The for loop has
the following syntax:
for (statement 1; statement 2; statement 3)
{
the code block to be executed
}
{
the code block to be executed
}
Statement
1 is executed before the loop (the code block) starts.
Statement
2 defines the condition for running the loop (the code block).
Statement
3 is executed each time after the loop (the code block) has been
executed.
<!DOCTYPE
html>
<body>
<p
id="demo"></p>
<script>
var x
="";
for
(i=0;i<5;i++)
{
x= x + " The number is " + i +
"<br>";
}
document.getElementById("demo").innerHTML=x;
</script></body></html>
From the example
above, you can read:
Statement 1 sets
a variable before the loop starts (var i=0).
Statement 2
defines the condition for the loop to run (i must be less than 5).
Statement 3
increases a value (i++) each time the code block in the loop has been executed.
Statement 1
Normally you
will use statement 1 to initiate the variable used in the loop (var i=0).
This is not
always the case, JavaScript doesn't care, and statement 1 is optional.
You can initiate
any (or many) values in statement 1:
for (var i=0,len=cars.length; i<len; i++)
{
document.write(cars[i] + "<br>");
}
{
document.write(cars[i] + "<br>");
}
And you can omit
statement 1 (like when your values are set before the loop starts):
Example:
var i=2,len=cars.length;
for (; i<len; i++)
{
document.write(cars[i] + "<br>");
}
for (; i<len; i++)
{
document.write(cars[i] + "<br>");
}
Statement 2
It is optional.
If statement 2 returns true, the loop will start over again, if it returns
false, the loop will end.
If you omit statement 2, you must provide a break inside the loop. Otherwise the loop will
never end. This will crash your browser. Read about breaks in a later chapter
of this tutorial.
Statement 3
Also is
optional. The increment could be negative (i--), or larger (i=i+15). Statement
3 can also be omitted (like when you have corresponding code inside the loop):
var i=0,len=cars.length;
for (; i<len; )
{
document.write(cars[i] + "<br>");
i++;
}
for (; i<len; )
{
document.write(cars[i] + "<br>");
i++;
}
The For/In Loop
The JavaScript
for/in statement loops through the properties of an object:
<!DOCTYPE
html>
<html>
<body>
<button
onclick="myfunction()">try it</button>
<p
id="demo"></p>
<script>
function
myfunction()
{
var x ;
var txt = ""
var
person={fname:"yasser",job:"programmer",age:40};
for (x in person)
{
txt =txt + person[x] +
"<br>";
document.getElementById("demo").innerHTML=txt;
}
}
</script></body></html>
JavaScript While Loop
Loops
can execute a block of code as long as a specified condition is true.
The While Loop
The while loop
loops through a block of code as long as a specified condition is true.
<!DOCTYPE html>
<body>
<button
onclick="myfunction()">try it</button>
<p id="demo"></p>
<script>
function myfunction()
{
var x = "", i= 0;
while (i<5)
{
x=
x + " number is " + i + "<br>";
i++;
}
document.getElementById("demo").innerHTML=x;
}
</script></body></html>
If you forget to increase the variable used
in the condition, the loop will never end. This will crash your browser.
The Do/While Loop
The do/while
loop is a variant of the while loop. This loop will execute the code block
once, before checking if the condition is true, then it will repeat the loop as
long as the condition is true.
The example
below uses a do/while loop. The loop will always be executed at least once,
even if the condition is false, because the code block is executed before the
condition is tested:
Example
do
{
x=x + "The number is " + i + "<br>";
i++;
}
while (i<5);
{
x=x + "The number is " + i + "<br>";
i++;
}
while (i<5);
The Break Statement
You have already
seen the break statement used in an earlier chapter of this tutorial. It was
used to "jump out" of a switch() statement.
The break
statement can also be used to jump out of a loop.
The break
statement breaks the loop and continues executing the code after the
loop (if any):
The break statement "jumps
out" of a loop.
The continue statement "jumps
over" one iteration in the loop.
for (i=0;i<10;i++)
{
if (i==3)
{
break;
}
x=x + "The number is " + i + "<br>";
}
{
if (i==3)
{
break;
}
x=x + "The number is " + i + "<br>";
}
Since the if statement has only one single line of code, the braces can be omitted:
for (i=0;i<10;i++)
{
if (i==3) break;
x=x + "The number is " + i + "<br>";
}
{
if (i==3) break;
x=x + "The number is " + i + "<br>";
}
The Continue Statement
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.This example skips the value of 3:
Example
for (i=0;i<=10;i++)
{
if (i==3) continue;
x=x + "The number is " + i + "<br>";
}
{
if (i==3) continue;
x=x + "The number is " + i + "<br>";
}
JavaScript Labels
As you have
already seen, in the chapter about the switch statement, JavaScript statements
can be labeled.
To label
JavaScript statements you precede the statements with a colon:
label:
statements
statements
The break and
the continue statements are the only JavaScript statements that can "jump
out of" a code block.
Syntax:
break labelname;
continue labelname;
continue labelname;
The continue
statement (with or without a label reference) can only be used inside a loop.
The break
statement, without a label reference, can only be used inside a loop or a
switch.
With a label
reference, it can be used to "jump out of" any JavaScript code block:
<!DOCTYPE
html>
<html>
<body>
<script>
cars=["BMW","Volvo","Saab","Ford"];
list:
{
document.write(cars[0]
+ "<br>");
document.write(cars[1]
+ "<br>");
document.write(cars[2]
+ "<br>");
break list;
document.write(cars[3]
+ "<br>");
document.write(cars[4]
+ "<br>");
document.write(cars[5]
+ "<br>");
}
</script></body>
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.
When the
JavaScript engine is executing JavaScript code, different errors can occur:
It can be syntax
errors, typically coding errors or typos made by the programmer.
It can be
misspelled or missing features in the language (maybe due to browser
differences).
It can be errors
due to wrong input, from a user, or from an Internet server.
And, of course,
it can be many other unforeseeable things.
JavaScript Throws Errors
When an error
occurs, when something goes wrong, the JavaScript engine will normally stop,
and generate an error message.
The technical
term for this is: JavaScript will throw an error.
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.
<!DOCTYPE html><html>
<body>
<button onclick="myfunction()">try it</button>
<script>
function myfunction()
{
try
{
adddd("welcome guest!");
}
catch (err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
}
</script></body></html>
The Throw Statement
The throw
statement allows you to create a custom error. The correct technical term is to
create or throw an exception. If you use the throw statement
together with try and catch, you can control program flow and generate custom
error messages. The exception can be a JavaScript String, a Number, a Boolean
or an Object.
This example
examines the value of an input variable. If the value is wrong, an exception
(error) is thrown. The error is caught by the catch statement and a custom
error message is displayed:
<!DOCTYPE html><body>
<script>
function myFunction()
{
y=document.getElementById("mess");
y.innerHTML="";
try
{
x=document.getElementById("demo").value;
if(x=="") throw "empty";
if(isNaN(x)) throw "not a number";
if(x>10) throw "too high";
if(x<5) throw "too low";
}
catch(err)
{
y.innerHTML="Error: " + err + ".";
}
}
</script>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="mess"></p>
</body>
</html>
Note that the example above will also throw an error if the getElementById function fails.
JavaScript Form Validation
JavaScript can
be used to validate data in HTML forms before sending off the content to a
server.
Form data that
typically are checked by a JavaScript could be:
- has the user left required fields empty?
- has the user entered a valid e-mail address?
- has the user entered a valid date?
- has the user entered text in a numeric field?
Required Fields
The function below checks if a
field has been left empty. If the field is blank, an alert box alerts a
message, the function returns false, and the form will not be submitted:
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
<!DOCTYPE html>{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
E-mail Validation
The function
below checks if the content has the general syntax of an email.
This means that
the input data must contain an @ sign and at least one dot (.). Also, the @
must not be the first character of the email address, and the last dot must be
present after the @ sign, and minimum 2 characters before the end:
<!DOCTYPE html><html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form></body></html>
JavaScript Objects
"Everything" in JavaScript is an Object.
In addition, JavaScript allows you to define your own objects.
Everything is an Object
In JavaScript
almost everything is an object. Even primitive datatypes (except null and
undefined) can be treated as objects.
- Booleans can be objects or primitive data treated as objects
- Numbers can be objects or primitive data treated as objects
- Strings are also objects or primitive data treated as objects
- Dates are always objects
- Maths and Regular Expressions are always objects
- Arrays are always objects
- Even functions are always objects
JavaScript Objects
An object is
just a special kind of data, with properties and methods.
Accessing Object Properties
Properties are
the values associated with an object.
The syntax for
accessing the property of an object is:
objectName.propertyName
This example
uses the length property of the String object to find the length of a string:
var message="Hello World!";
var x=message.length;
var x=message.length;
The value of x, after execution of
the code above will be: 12
Accessing Objects Methods
Methods are the
actions that can be performed on objects.
You can call a
method with the following syntax:
objectName.methodName()
This example
uses the toUpperCase() method of the String object, to convert a text to
uppercase:
var message="Hello world!";
var x=message.toUpperCase();
var x=message.toUpperCase();
The value of x,
after execution of the code above will be: HELLO WORLD!
Creating JavaScript Objects
With JavaScript
you can define and create your own objects.
There are 2
different ways to create a new object:
- 1. Define and create a direct instance of an object.
- 2. Use a function to define an object, then create new object instances.
Creating a Direct Instance
The following
example creates a new instance of an object, and adds four properties to it:
person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
Using an Object Constructor
The following
example uses a function to construct the object:
<!DOCTYPE
html><html><body><script>
function
person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
myFather=new
person("John","Doe",50,"blue");
document.write(myFather.firstname +
" is " + myFather.age + " years old.");
</script></body></html>
The reason for
all the "this" stuff is that you're going to have more than one
person at a time (which person you're dealing with must be clear). That's what
"this" is: the instance of the object at hand.
Creating JavaScript Object Instances
Once you have a
object constructor, you can create new instances of the object, like this:
var myFather=new
person("John","Doe",50,"blue");
var myMother=new person("Sally","Rally",48,"green");
var myMother=new person("Sally","Rally",48,"green");
Adding Properties to JavaScript Objects
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:
person.nationality="English";
x=person.nationality;
x=person.nationality;
The value of x,
after execution of the code above will be: English
No comments:
Post a Comment