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

Unit II Javascript

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit II Javascript

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 69

JAVASCRIPT

Client Side Scripting


Javascript

BASICS OF JAVASCRIPT
Javascript
 JavaScript is a simple scripting language invented specifically for use in web
browsers to make websites more dynamic.
 JavaScript is a client-side language, which means all the action occurs on the client's
side of things.
 JavaScripts are integrated into the browsing environment, which means they can get
information about the browser and HTML page, and modify this information, thus
changing how things are presented on users screen.
Advantages of JavaScript
 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
 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.

Syntax of JavaScript
<script ...>
JavaScript code
</script>

NMC
JAVASCRIPT

JAVASCRIPT VARIABLES

 JavaScript variables are containers for storing data values.


 All JavaScript variables must be identified with unique names.
 These unique names are called identifiers.
 Variables are declared with the var keyword
 Javascript variable can hold a value of any data type.
 The value type of a variable can change during the execution of a program and
Javascript takes care of it automatically.

General rules for constructing names for variables (unique identifiers)


 Names can contain letters, digits, underscores, and dollar signs.
 Names must begin with a letter
 Names can also begin with $ and _
 Names are case sensitive (y and Y are different variables)
 Reserved words (like JavaScript keywords) cannot be used as names

Example
<script type="text/javascript">
<!--
var name = "Aravind";
var money;
money = 10000;
//-->
</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.

NMC
JAVASCRIPT

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>
This produces the following result −
local

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

NMC
JAVASCRIPT

JAVASCRIPT STRINGS

 JavaScript strings are used for storing and manipulating text.


 A JavaScript string is zero or more characters written inside quotes.
 You can use single or double quotes:
 You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:

Example
var answer1 = "It's alright";
var answer2 = "He is called 'Johnny'";
var answer3 = 'He is called "Johnny"';

Special Characters
Code Result Description
\' ' Single quote
\" " Double quote
\\ \ Backslash

1.charAt() Method
Return the first character of a string

//charAt()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the last character of the string "HELLO WORLD".</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "HELLO WORLD";
var res = str.charAt(str.length-1);
document.getElementById("demo").innerHTML = res;
}

NMC
JAVASCRIPT

</script>

</body>
</html>

2.concat() Method

Join two strings

//concat()
//Date 26/02/19

<!DOCTYPE html>
<html>
<body>
<p>Click the button to join two strings into one new string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str1 = "Hello ";
var str2 = "world!";
var res = str1.concat(str2);
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>

3. String length

Return the number of characters in a string

//length()
//Date 26/02/19
<!DOCTYPE html>
<html>

NMC
JAVASCRIPT

<body>
<p>Click the button to return the number of characters in the string "Hello World!".</p>

<button onclick="myFunction()">Try it</button>


<p id="demo"></p>
<script>
function myFunction() {
var str = "Hello World!";
var n = str.length;
document.getElementById("demo").innerHTML = n;
}
</script>
</body>
</html>

4. toUpperCase() Method
Convert the string to uppercase letters

//toUppercase()
//Date 26/02/19

<!DOCTYPE html>
<html>
<body>
<p>Click the button to convert the string to uppercase letters.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Hello World!";
var res = str.toUpperCase();
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>

NMC
JAVASCRIPT

5. toLowerCase() Method
Convert the string to lowercase letters

//toLowerCase()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<p>Click the button to convert the string to lowercase letters.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Hello World!";
var res = str.toLowerCase();
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>

6. String match()

 The match() method searches a string for a match against a regular expression, and
returns the matches, as an Array object.
 This method returns null if no match is found.

//str.match()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<p>Click the button to perfom a global search for the letters "ain" in a string, and display
the matches.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {

NMC
JAVASCRIPT

var str = "The rain in SPAIN stays mainly in the plain";


var res = str.match(/ain/g);
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>

//String Manipulation
//Date 26/02/19

<script language="JavaScript">
// Define a global search string.
var SearchString = "This is the search string!"
function FindString()
{
// Obtain the value the user wants to find.
var FindValue =
document.getElementById("SearchString").value;
// Perform the search.
var Result = SearchString.indexOf(FindValue);
// Display an appropriate result.
// Check for a blank input first.
if (Result == 0)
{
document.getElementById("Result").innerHTML =
"You must provide an input value!";
}
// Check for a result that doesn't exist next.
else if (Result == -1)
{
document.getElementById("Result").innerHTML =
"The search string doesn't exist.";
}
// Display the location information.
else
{
document.getElementById("Result").innerHTML =
'The search string "' + FindValue +
'" appears at character ' + Result;
}

NMC
JAVASCRIPT

}
</script>

JAVASCRIPT MATHEMATICAL FUNCTIONS

Math Functions in JavaScript


1. Math.abs(a) // the absolute value of a
2. Math.cos(a) // cosine of a
3. Math.sin(a) // sine of a
4. Math.round(a) // integer closest to a
5. Math.pow(a,b) // a to the power b
6. Math.sqrt(a) // square root of a
7. Math.ceil(a) // integer closest to a and not less than a
8. Math.floor(a) // integer closest to a, not greater than a
9. Math.max(a,b) // the maximum of a and b
10. Math.min(a,b) // the minimum of a and b
11. Math.random() // pseudorandom number 0 to 1

1. Math.abs ()
Math.abs(x) returns the absolute (positive) value of x

//Math.abs()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.abs()</h2>
<p>Math.abs(x) returns the absolute (positive) value of x:</p>
<p id="demo"></p>

NMC
JAVASCRIPT

<script>
document.getElementById("demo").innerHTML = Math.abs(-4.4);
</script>
</body>
</html>

Output
JavaScript Math.abs()
Math.abs(x) returns the absolute (positive) value of x:
4.4

2. Math.cos()
Math.cos(x) returns the cosine (a value between -1 and 1) of the angle x (given in
radians).
If you want to use degrees instead of radians, you have to convert degrees to radians:
Angle in radians = Angle in degrees x PI / 180.

//Mat
h.cos()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.cos()</h2>
<p>Math.cos(x) returns the cosin of x (given in radians):</p>
<p>Angle in radians = (angle in degrees) * PI / 180.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"The cosine value of 0 degrees is " + Math.cos(0 * Math.PI / 180);
</script>
</body>
</html>

Output
JavaScript Math.cos()
Math.cos(x) returns the cosin of x (given in radians):
Angle in radians = (angle in degrees) * PI / 180.
The cosine value of 0 degrees is 1

NMC
JAVASCRIPT

3. Math.sin()
Math.sin(x) returns the sine (a value between -1 and 1) of the angle x (given in
radians).
If you want to use degrees instead of radians, you have to convert degrees to radians:
Angle in radians = Angle in degrees x PI / 180.

//Math.sin()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.sin()</h2>
<p>Math.sin(x) returns the sin of x (given in radians):</p>
<p>Angle in radians = (angle in degrees) * PI / 180.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"The sine value of 90 degrees is " + Math.sin(90 * Math.PI / 180);
</script>
</body>
</html>

Output
JavaScript Math.sin()
Math.sin(x) returns the sin of x (given in radians):
Angle in radians = (angle in degrees) * PI / 180.
The sine value of 90 degrees is 1

4. Math.round()
Math.round(x) returns the value of x rounded to its nearest integer

NMC
JAVASCRIPT

//Math.round()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.round()</h2>
<p>Math.round(x) returns the value of x rounded to its nearest integer:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.round(4.4);
</script>
</body>
</html>

Output

JavaScript Math.round()
Math.round(x) returns the value of x rounded to its nearest integer:

5. Math.pow()

Math.pow(x, y) returns the value of x to the power of y

//Math.pow()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.pow()</h2>
<p>Math.pow(x,y) returns the value of x to the power of y:</p>

NMC
JAVASCRIPT

<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.pow(8,2);
</script>
</body>
</html>

Output

JavaScript Math.pow()

Math.pow(x,y) returns the value of x to the power of y:

64

6. Math.sqrt()

Math.sqrt(x) returns the square root of x

//Math.sqrt()
//Date 26/02/19
<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Math.sqrt()</h2>

<p>Math.sqrt(x) returns the square root of x:</p>

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

<script>

document.getElementById("demo").innerHTML = Math.sqrt(64);

NMC
JAVASCRIPT

</script>

</body>

</html>

Output

JavaScript Math.sqrt()

Math.sqrt(x) returns the square root of x:

7. Math.ceil()

Math.ceil(x) returns the value of x rounded up to its nearest integer

//Math.ceil

//Date 26/02/19

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Math.ceil()</h2>

<p>Math.ceil() rounds a number <strong>up</strong> to its nearest integer:</p>

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

<script>

document.getElementById("demo").innerHTML = Math.ceil(4.4);

</script>

</body>

NMC
JAVASCRIPT

</html>

Output

JavaScript Math.ceil()

Math.ceil() rounds a number up to its nearest integer:

8. Math.floor()

Math.floor(x) returns the value of x rounded down to its nearest integer

//Math.floor()
//Date 26/02/19
<!DOCTYPE html>

<html>
<body>
<h2>JavaScript Math.floor()</h2>
<p>Math.floor(x) returns the value of x rounded <strong>down</strong> to its nearest
integer:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.floor(4.7);
</script>
</body>
</html>

Output

NMC
JAVASCRIPT

JavaScript Math.floor()

Math.floor(x) returns the value of x rounded down to its nearest integer:

9. Math.min() and Math.max()

Math.min() and Math.max() can be used to find the lowest or highest value in a list
of arguments

//Math.min() and Mat.max()


//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.min()</h2>
<p>Math.min() returns the lowest value in a list of arguments:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
Math.min(0, 150, 30, 20, -8, -200);
</script>
</body>
</html>

Output

JavaScript Math.min()

Math.min() returns the lowest value in a list of arguments:

NMC
JAVASCRIPT

-200

10. Math.random()

Math.random() returns a random number between 0 (inclusive), and 1 (exclusive)

//Math.random()
//Date 26/02/19
<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Math.random()</h2>

<p>Math.random() returns a random number between 0 and 1:</p>

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

<script>

document.getElementById("demo").innerHTML = Math.random();

</script>

</body>

</html>

Output

JavaScript Math.random()

Math.random() returns a random number between 0 and 1:

0.9883295168385227

NMC
JAVASCRIPT

Math Properties (Constants)


JavaScript provides 8 mathematical constants that can be accessed with the Math
object:

//Math constants
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math Constants</h2>

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

<script>
document.getElementById("demo").innerHTML =
"<p><b>Math.E:</b> " + Math.E + "</p>" +
"<p><b>Math.PI:</b> " + Math.PI + "</p>" +
"<p><b>Math.SQRT2:</b> " + Math.SQRT2 + "</p>" +
"<p><b>Math.SQRT1_2:</b> " + Math.SQRT1_2 + "</p>" +
"<p><b>Math.LN2:</b> " + Math.LN2 + "</p>" +
"<p><b>Math.LN10:</b> " + Math.LN10 + "</p>" +
"<p><b>Math.LOG2E:</b> " + Math.LOG2E + "</p>" +
"<p><b>Math.Log10E:</b> " + Math.LOG10E + "</p>";
</script>

</body>
</html>

Output

JavaScript Math Constants

Math.E: 2.718281828459045

Math.PI: 3.141592653589793

NMC
JAVASCRIPT

Math.SQRT2: 1.4142135623730951

Math.SQRT1_2: 0.7071067811865476

Math.LN2: 0.6931471805599453

Math.LN10: 2.302585092994046

Math.LOG2E: 1.4426950408889634

Math.Log10E: 0.4342944819032518

JAVASCRIPT STATEMENTS

JavaScript - if...else Statement


 JavaScript supports conditional statements which are used to perform different actions
based on different conditions.

NMC
JAVASCRIPT

Flow chart

JavaScript supports the following forms of if..else statement


1. if statement
2. if...else statement
3. if...else if... statement.
1.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
}
 Here a JavaScript expression is evaluated. If the resulting value is true, the given
statement(s) are executed.
 If the expression is false, then no statement would be not executed.
Most of the times, user will use comparison operators while making decisions.
//if statement
//Date 26/02/19

<html>

NMC
JAVASCRIPT

<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...

2.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
}
Here JavaScript expression is evaluated. If the resulting value is true, the given
statement(s) in the ‘if’ block, are executed. If the expression is false, then the given
statement(s) in the else block are executed.
//if..else
//Date 26/02/19

<html>
<body>

NMC
JAVASCRIPT

<script type="text/javascript">
<!--
var age = 15;

if( age > 18 ){


document.write("<b>Qualifies for driving</b>");
}

else{
document.write("<b>Does not qualify for driving</b>");
}
//-->
</script>

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


</body>
</html>
Output
Does not qualify for driving
Set the variable to different value and then try...

3.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{

NMC
JAVASCRIPT

Statement(s) to be executed if no expression is true


}
 There is nothing special about this code. It is just a series of if statements, where
each if is a part of the else clause of the previous statement.
 Statement(s) are executed based on the true condition, if none of the conditions is
true, then the else block is executed.
//if..elseif
//Date 26/02/19

<html>
<body>

<script type="text/javascript">
<!--
var book = "maths";
if( book == "history" ){
document.write("<b>History Book</b>");
}

else if( book == "maths" ){


document.write("<b>Maths Book</b>");
}

else if( book == "economics" ){


document.write("<b>Economics Book</b>");
}

else{
document.write("<b>Unknown Book</b>");
}
//-->
</script>

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


</body>
</html>
Output
Maths Book
Set the variable to different value and then try...

NMC
JAVASCRIPT

JavaScript - Switch Case


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.

Flow Chart

Syntax
switch (expression)
{
case condition 1: statement(s)
break;

case condition 2: statement(s)


break;
...

case condition n: statement(s)


break;

NMC
JAVASCRIPT

default: statement(s)
}
.
//Switch statement
//Date 26/02/19

<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

NMC
JAVASCRIPT

Exiting switch block


Set the variable to different value and then try...

Break Statements
Break statements play a major role in switch-case statements.

<html>
<body>

<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
case 'A': document.write("Good job<br />");
case 'B': document.write("Pretty good<br />");
case 'C': document.write("Passed<br />");
case 'D': document.write("Not so good<br />");
case 'F': document.write("Failed<br />");
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
Pretty good
Passed
Not so good
Failed
Unknown grade
Exiting switch block
Set the variable to different value and then try...

NMC
JAVASCRIPT

JavaScript - Looping Statement


Loops in JavaScript are used to execute the same block of code a specified
number of times or while a specified condition is true.

1.For Loop :
Loops through a block of code a specified number of times

Syntax:
for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}

 The condition expression is evaluated. If the value of condition is true, the loop
statements execute. If the value of condition is false, the for loop terminates.
 The statements execute.

//for loop
//Date 26/02/19
<html>
<body>
<script language=“javascript”>
for (i = 1; i <= 6; i++)
{
document.write("<h" + i + ">Visions Developer " + i);
document.write("</h" + i + ">");
}
</script>
</body>
</html>

2.While Loop :
Loops through a block of code while a specified condition is true while loop, is used
to run the same block of code while a specified condition is true.

Syntax:

while (var<=endvalue)
{
code to be executed

NMC
JAVASCRIPT

//while loop
//Date 26/02/19
<html>
<body>
<script language=“javascript”>
var i=0
while (i<=10)
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
</script>
</body>
</html>

3.Do….While Loop
The do...while statement repeats until a specified condition evaluates to false.
Syntax:
do
{
statement
} while

Statement executes once before the condition is checked. If condition returns true,
the statement executes again.
At the end of every execution, the condition is checked. When the condition
returns false, execution stops and control passes to the statement following
do...while.
//Do..while
//Date 26/02/19
<html>
<body>
<script language=“javascript”>
i=0;
do
{
i++;
document.write(i);

NMC
JAVASCRIPT

} while (i<5);
</script>
</body>
</html>

JAVASCRIPT OPERATORS

OPERATOR
-->JavaScript operators are used to assign values, compare values, perform arithmetic
operations, and more..
Types of operators
1. Arithmetic Operators
2. Comparison Operators
3. Logical (or Relational) Operators
4. Assignment Operators
5. Conditional (or ternary) Operators
1. ARITHMETIC OPERATORS
JavaScript supports the following arithmetic operators −
Assume variable A holds 10 and variable B holds 20, then −
Sr.No Operator and Description
1 + (Addition)
Adds two operands
Ex: A + B will give 30
2 - (Subtraction)
Subtracts the second operand from the first
Ex: A - B will give -10
3 * (Multiplication)
Multiply both operands
Ex: A * B will give 200
4 / (Division)
Divide the numerator by the denominator
Ex: B / A will give 2
5 % (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0
6 ++ (Increment)
Increases an integer value by one
NMC
JAVASCRIPT

Ex: A++ will give 11


7 -- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9
Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will
give "a10".
Example
The following code shows how to use arithmetic operators in JavaScript.
//Arithmetic operators.html
//date 14/12/18
<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;

NMC
JAVASCRIPT

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...

2. COMPARISON OPERATORS
JavaScript supports the following comparison operators −
Assume variable A holds 10 and variable B holds 20, then −
Sr.No Operator and Description
1 = = (Equal)
Checks if the values of two operands are equal or not, if yes, then the condition
becomes true.
Ex: (A == B) is not true.
2 != (Not Equal)

NMC
JAVASCRIPT

Checks if the value of two operands are equal or not, if the values are not equal,
then the condition becomes true.
Ex: (A != B) is true.
3 > (Greater than)
Checks if the value of the left operand is greater than the value of the right
operand, if yes, then the condition becomes true.
Ex: (A > B) is not true.
4 < (Less than)
Checks if the value of the left operand is less than the value of the right operand,
if yes, then the condition becomes true.
Ex: (A < B) is true.
5 >= (Greater than or Equal to)
Checks if the value of the left operand is greater than or equal to the value of the
right operand, if yes, then the condition becomes true.
Ex: (A >= B) is not true.
6 <= (Less than or Equal to)
Checks if the value of the left operand is less than or equal to the value of the
right operand, if yes, then the condition becomes true.
Ex: (A <= B) is true.

Example
The following code shows how to use comparison operators in JavaScript.
<html>
<body>

<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";

document.write("(a == b) => ");


result = (a == b);
document.write(result);
document.write(linebreak);

document.write("(a < b) => ");


result = (a < b);

NMC
JAVASCRIPT

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) => ");


result = (a <= b);
document.write(result);
document.write(linebreak);
//-->
</script>

Set the variables to different values and different operators and then try...
</body>
</html>
Output
(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
a <= b) => true
Set the variables to different values and different operators and then try...

3.LOGICAL OPERATORS
JavaScript supports the following logical operators −
Assume variable A holds 10 and variable B holds 20, then −
Sr.No Operator and Description

NMC
JAVASCRIPT

1 && (Logical AND)


If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.
2 || (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
3 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical
NOT operator will make it false.
Ex: ! (A && B) is false.

Example

<html>
<body>

<script type="text/javascript">
<!--
var a = true;
var b = false;
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);
//-->
</script>

<p>Set the variables to different values and different operators and then try...</p>

NMC
JAVASCRIPT

</body>
</html>
Output
(a && b) => false
(a || b) => true
!(a && b) => true
Set the variables to different values and different operators and then try...

4.BITWISE OPERATORS
JavaScript supports the following bitwise operators −
Assume variable A holds 2 and variable B holds 3, then −
Sr.No Operator and Description
1 & (Bitwise AND)
It performs a Boolean AND operation on each bit of its integer arguments.
Ex: (A & B) is 2.
2 | (BitWise OR)
It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.
3 ^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its integer
arguments. Exclusive OR means that either operand one is true or operand two
is true, but not both.
Ex: (A ^ B) is 1.
4 ~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand.
Ex: (~B) is -4.
5 << (Left Shift)
It moves all the bits in its first operand to the left by the number of places
specified in the second operand. New bits are filled with zeros. Shifting a value
left by one position is equivalent to multiplying it by 2, shifting two positions is
equivalent to multiplying by 4, and so on.
Ex: (A << 1) is 4.
6 >> (Right Shift)
Binary Right Shift Operator. The left operand’s value is moved right by the
number of bits specified by the right operand.

NMC
JAVASCRIPT

Ex: (A >> 1) is 1.
7 >>> (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.
Example

<html>
<body>

<script type="text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
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("(~b) => ");


result = (~b);
document.write(result);
document.write(linebreak);

document.write("(a << b) => ");


result = (a << b);
document.write(result);
document.write(linebreak);

document.write("(a >> b) => ");

NMC
JAVASCRIPT

result = (a >> b);


document.write(result);
document.write(linebreak);
//-->
</script>

<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
Set the variables to different values and different operators and then try...

5. ASSIGNMENT OPERATORS
JavaScript supports the following assignment operators −
Sr.No Operator and Description
1 = (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C
2 += (Add and Assignment)
It adds the right operand to the left operand and assigns the result to the left
operand.
Ex: C += A is equivalent to C = C + A
3 −= (Subtract and Assignment)
It subtracts the right operand from the left operand and assigns the result to the
left operand.
Ex: C -= A is equivalent to C = C - A
4 *= (Multiply and Assignment)
It multiplies the right operand with the left operand and assigns the result to the
left operand.
Ex: C *= A is equivalent to C = C * A
5 /= (Divide and Assignment)
It divides the left operand with the right operand and assigns the result to the left
operand.

NMC
JAVASCRIPT

Ex: C /= A is equivalent to C = C / A
6 %= (Modules and Assignment)
It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A
Note − Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=,
&=, |= and ^=.
Example

<html>
<body>

<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";

document.write("Value of a => (a = b) => ");


result = (a = b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a += b) => ");


result = (a += b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a -= b) => ");


result = (a -= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a *= b) => ");


result = (a *= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a /= b) => ");


result = (a /= b);
document.write(result);
document.write(linebreak);

NMC
JAVASCRIPT

document.write("Value of a => (a %= b) => ");


result = (a %= b);
document.write(result);
document.write(linebreak);
//-->
</script>

<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Output
Value of a => (a = b) => 10
Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) => 0
Set the variables to different values and different operators and then try...

6. MISCELLANEOUS OPERATOR
conditional operator (? :) and the typeof operator.

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.

Sr.No Operator and Description


1 ? : (Conditional )
If Condition is true? Then value X : Otherwise value
Y
Example
<html>
<body>

<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";

NMC
JAVASCRIPT

document.write ("((a > b) ? 100 : 200) => ");


result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);

document.write ("((a < b) ? 100 : 200) => ");


result = (a < b) ? 100 : 200;
document.write(result);
document.write(linebreak);
//-->
</script>

<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Output
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
Set the variables to different values and different operators and then try...

typeof Operator
 The typeof operator is a unary operator that is placed before its single operand,
which can be of any type. Its value is a string indicating the data type of the
operand.
 The typeof operator evaluates to "number", "string", or "boolean" if its operand is
a number, string, or boolean value and returns true or false based on the
evaluation.
Here is a list of the return values for the typeof Operator.

Type String Returned by


typeof
Number "number"
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefine "undefined"
d
Null "object"

NMC
JAVASCRIPT

Example
The following code shows how to implement typeof operator.
<html>
<body>

<script type="text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";

result = (typeof b == "string" ? "B is String" : "B is Numeric");


document.write("Result => ");
document.write(result);
document.write(linebreak);

result = (typeof a == "string" ? "A is String" : "A is Numeric");


document.write("Result => ");
document.write(result);
document.write(linebreak);
//-->
</script>

<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

Output
Result => B is String
Result => A is Numeric
Set the variables to different values and different operators and then try...

NMC
JAVASCRIPT

JAVASCRIPT ARRAYS

JavaScript arrays are used to store multiple values in a single variable.

Syntax:
var array_name = [item1, item2, ...];

//Javascript arrays
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>The best way to loop through an array is using a standard for loop:</p>
<p id="demo"></p>
<script>
var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Javascript Arrays Sort


The sort() method sorts an array alphabetically.

NMC
JAVASCRIPT

//Sort()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array Sort</h2>
<p>The sort() method sorts an array alphabetically.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
function myFunction() {
fruits.sort();
document.getElementById("demo").innerHTML = fruits;
}
</script>
</body>
</html>

Numeric Sort
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array Sort</h2>
<p>Click the button to sort the array in ascending order.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;
function myFunction() {
points.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = points;
}
</script>

NMC
JAVASCRIPT

</body>
</html>

JAVASCRIPT FUNCTIONS
JavaScript - Functions
 JavaScript functions are defined with the function keyword.

Function Declarations

Declared functions are not executed immediately. They are "saved for later use", and will
be executed later, when they are invoked (called upon).

syntax:

function functionName(parameters) {
// code to be executed
}

//Javascript functions
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation and returns the
result:</p>
<p id="demo"></p>

NMC
JAVASCRIPT

<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}
</script>
</body>
</html>

Function Expressions

A JavaScript function can also be defined using an expression.

A function expression can be stored in a variable

//Function expression
<!DOCTYPE html>
<html>
<body>
<p>After a function has been stored in a variable,
the variable can be used as a function:</p>
<p id="demo"></p>
<script>
var x = function (a, b) {return a * b};
document.getElementById("demo").innerHTML = x(4, 3);
</script>
</body>
</html>

NMC
JAVASCRIPT

Output

After a function has been stored in a variable, the variable can be used as a
function:

12

Function Parameters
There is a facility to pass different parameters while calling a function.
 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.
//function parameter

<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">

NMC
JAVASCRIPT

</form>

<p>Use different parameters inside the function and then try...</p>

</body>

</html>

return Statement

 A JavaScript function can have an optional return statement.

 This is required if you want to return a value from a function. This statement

should be the last statement in a function.


//return statement

<html>

<head>

<script type = "text/javascript">

function concatenate(first, last) {

var full;

full = first + last;

return full;

function secondFunction() {

var result;

NMC
JAVASCRIPT

result = concatenate('Zara', 'Ali');

document.write (result );

</script>

</head>

<body>

<p>Click the following button to call the function</p>

<form>

<input type = "button" onclick = "secondFunction()" value = "Call Function">

</form>

<p>Use different parameters inside the function and then try...</p>

</body>

</html>

JAVASCRIPT OBJECTS

Javascript objects are containers for named values called properties or methods.

Creating a JavaScript Object

With JavaScript, user can define and create your own objects.

Different ways to create new objects:

NMC
JAVASCRIPT

 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.

Syntax for adding a property to an object


objectName.objectProperty = propertyValue; //Javascript Objects

<!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>

Accessing Object Methods

An object method is a function definition, stored as a property value.

syntax:

objectName.methodName()

NMC
JAVASCRIPT

//Javascript object
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p>An object method is a function definition, stored as a property value.</p>
<p id="demo"></p>
<script>
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

// Display data from the object:

document.getElementById("demo").innerHTML = person.fullName();
</script>
</body>
</html>

Javascript method

A method is actually a function definition stored as a property value.

NMC
JAVASCRIPT

<!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>

NMC
JAVASCRIPT

REGULAR EXPRESSIONS

A regular expression is an object that describes a pattern of characters.


The JavaScript RegExp class represents regular expressions, and both String
and RegExp define methods that use regular expressions to perform powerful pattern-
matching and search-and-replace functions on text.
Syntax

var pattern = new RegExp(pattern, attributes);

or simply

var pattern = /pattern/attributes;


Here is the description of the parameters −
 pattern − A string that specifies the pattern of the regular expression or another
regular expression.
 attributes − An optional string containing any of the "g", "i", and "m" attributes
that specify global, case-insensitive, and multiline matches, respectively.
Examples

Sr.No Expression & Description

1 [^a-zA-Z]
It matches any string not containing any of the characters ranging
from a through z and A through Z.

2 p.p
It matches any string containing p, followed by any character, in turn
followed by another p.

3 ^.{2}$
It matches any string containing exactly two characters.

4 <b>(.*)</b>

NMC
JAVASCRIPT

It matches any string enclosed within <b> and </b>.

5 p(hp)*
It matches any string containing a p followed by zero or more instances of
the sequence hp.
RegExp Methods

Sr.No Method & Description


1 exec()
Executes a search for a match in its string parameter.
2 test()
Tests for a match in its string parameter.
3 toSource()
Returns an object literal representing the specified object; you can use this value
to create a new object.
4 toString()
Returns a string representing the specified object.

//swapping two words


//date 30/01/19
<html>
<head>
<title>swapping words</title>
</head>
<body>
<script language="javascript">
<!--
initial="this is a test string";
re="(test)*(string)"
finished=initial.replace(re,"$2 $1");
document.writeln("<h1>swapping words</h1><p>");
document.write(finished);
document.writeln("</p>");
document.close();
//-->
</script>

NMC
JAVASCRIPT

</body>
</html>

RegExp Object
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;
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Regular Expressions</h2>


<p>Click the button to do a case-insensitive search for "w3schools" in a string.</p>

<button onclick="myFunction()">Try it</button>


<p id="demo"></p>
<script>
function myFunction() {
var str = "Visit W3Schools";
var patt = /w3schools/i;
var result = str.match(patt);
document.getElementById("demo").innerHTML = result;
}
</script>

</body>
</html>

Output

NMC
JAVASCRIPT

EXCEPTION HANDLING
When a JavaScript statement generates an error, it is said to throw an exception. Instead
of proceeding to the next statement, the JavaScript interpreter checks forexception
handling code. If there is no exception handler, then the program returns from whatever
function threw the exception.

//EXCEPTION HANDLING
<!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="p01"></p>

<script>
function myFunction() {
var message, x;
message = document.getElementById("p01");
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>
OUTPUT

NMC
JAVASCRIPT

JAVASCRIPT EVENTS
Event
 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.
 Developers can use these events to execute JavaScript coded responses, which
cause buttons to close windows, messages to be displayed to users, data to be
validated, and virtually any other type of response imaginable.
 Events are a part of the Document Object Model (DOM) Level 3 and every
HTML element contains a set of events which can trigger JavaScript Code.
1. onclick Event Type
This is the most frequently used event type which occurs when a user clicks the left
button of his mouse. User can put your validation, warning etc., against this event type.
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>

NMC
JAVASCRIPT

</html>

2. 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.
Example
The following example shows how to use onsubmit. Here we are calling a validate
() function before submitting a form data to the web server. If validate () function
returns true, the form will be submitted, otherwise it will not submit the data.

<html>
<head>

<script type="text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>

</head>
<body>

<form method="POST" action="t.cgi" onsubmit="return validate()">


.......
<input type="submit" value="Submit" />
</form>

</body>
</html>

3.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.

NMC
JAVASCRIPT

<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 reference. Here script indicates a
Javascript function to be executed against that event.
Attribute Valu Description
e
onchange script Triggers when an element changes
onclick script Triggers on a mouse click
ondrag script Triggers when an element is dragged
onerror script Triggers when an error occur
oninput script Triggers when an element gets user input
oninvalid script Triggers when an element is invalid
onmousemov script Triggers when the mouse pointer moves
e
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

NMC
JAVASCRIPT

onsubmit script Triggers when a form is submitted


onsuspend script Triggers when the browser has been fetching media data, but stopped
before the entire media file was fetched

DYNAMIC HTML WITH JAVASCRIPT

DATA VALIDATION

//data validation
//date 4/2/19
<html>
<head>
<title>Data Validation</title>
</head>
<body>
<form method="post" action="addUser.php"
onSubmit="return Validate()">
<table border="0">
<tr>
<th>Your Name</th>
<td><input type="text" length="24" id="name"/></td>
</tr>
<tr>
<th>Your Age</th>
<td><input type="text" size="3" maxlength="3" id="age"/></td>
</tr>
<tr>
<td><input type="submit" value="submit"/></td>
<td><input type="reset" value="Reset"/></td>
</tr>
</table>
</form>
<script language="javascript">
<!--
function Validate()
{
var valid=false;
var name=document.getElementById("name").value;
var age=document.getElementById("age").value;

NMC
JAVASCRIPT

name_re=new RegExp("^[A-Z][a-zA-Z '-.]+$", "g");


age_re=new RegExp("^[\\\d]+$", "g");
if(name.match(name_re))
{
//onely validate the age if the name is OK
if(age.match(age_re))
{
//name and age are both valid
valid=true;
}
else
{
alert("Age does not match"+age_re);
}
}
else
{
alert("Name does not match"+name_re);
}
return valid;
}
//-->
</script>
</body>
</html>

JavaScript - Form Validation


 Form validation normally used to occur at the server, after the client had entered
all the necessary data and then pressed the Submit button.
 If the data entered by a client was incorrect or was simply missing, the server
would have to send all the data back to the client and request that the form be
resubmitted with correct information.
 This was really a lengthy process which used to put a lot of burden on the server.
JavaScript provides a way to validate form's data on the client's computer before sending
it to the web server.

NMC
JAVASCRIPT

Example

<html>

<head>
<title>Form Validation</title>

<script type="text/javascript">
<!--
// Form validation code will come here.
//-->
</script>

</head>

<body>
<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">

<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>

<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>

<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td>
</tr>

<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>

NMC
JAVASCRIPT

</td>
</tr>

<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>

</table>
</form>

</body>
</html>

OPENING A NEW WINDOW


opening a new window
<html>
<head>
<script language="javascript">
<!--
function Load(url)
{
var next=url;
newwin=open("url", "newwin",
'status=0,resizable=0,width=258,height=137'
);
}
//-->
</script>
</head>
<body>
<p>
<a href="" onclick="Load('./pic1.gif')">
show the next page
</a>
</body>
</html>
MESSAGES AND CONFIRMATIONS
<html>

NMC
JAVASCRIPT

<body>
<script
language="javascript">
<!--
prompt("Enter name")
confirm("Are you sure?")
alert("warning")
//-->
</script>
</body>
</html>

STATUS BAR
Status Bar
<html>
<head>
<script language="javascript">
<!--
function Init()
{
self.status="Chris's Message";
}
//-->
</script>
</head>
<body onLoad="Init()">
<h1>And the Status Bar Says...</h1>
</body>
</html>
WRITING TO A DIFFERENT FRAME

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01


Transitional//EN"><html><head><META http-equiv="Content-Type"
content="text/html; charset=utf-8"></head><body>
<div bgcolor="”white”" text="”red”">
<h1 align="center">Chris’s HomeBrew Color Picker</h1>
<form target="_blank" onsubmit="try {return window.confirm(&quot;This form may not
function properly due to certain security constraints.\nContinue?&quot;);} catch (e)
{return false;}">

NMC
JAVASCRIPT

<center><h2>Enter color values in the Boxes</h2></center>


<table align="”center”" border="”0”" cellpadding="”5”">
<tr>
<td>
<h3>background color</h3>
</td>
<td>
<input type="”textfield”" size="”16”" name="”bgcol”" value="”white”">
</td>
<td>
<h3>text color</h3>
</td>
<td>
<input type="”textfield”" size="”16”" name="”fgcol”" value="”black”">
</td>
</tr>
<tr>
<td>
<h3>table headings</h3>
</td>
<td>
<input type="”textfield”" size="”16”" name="”thcol”" value="”black”/">
</td>
<td>
<h3>table data</h3>
</td>
<td>
<input type="”textfield”" size="”16”" name="”tdcol”" value="”black”/">
</td>
</tr>
</table>
<input type="”button”" value="”show">
<input type="reset" value="Reset It">
</form>
</div>
</body></html>

</html>

NMC
JAVASCRIPT

Rollover buttons

Rollover with a Mouse Event


 At the time of loading this page, the ‘if’ statement checks for the existence of the
image object. If the image object is unavailable, this block will not be executed.
 The Image() constructor creates and preloads a new image object called image1.
 The src property is assigned the name of the external image file called
/images/html.gif.
 Similarly, we have created image2 object and assigned /images/http.gif in this
object.
 The # (hash mark) disables the link so that the browser does not try to go to a
URL when clicked. This link is an image.
 The onMouseOver event handler is triggered when the user's mouse moves onto
the link, and the onMouseOut event handler is triggered when the user's mouse
moves away from the link (image).
 When the mouse moves over the image, the HTTP image changes from the first
image to the second one. When the mouse is moved away from the image, the
original image is displayed.
 When the mouse is moved away from the link, the initial image html.gif will
reappear on the screen.

//Rollover image.html
//date 11/02/19
<html>

<head>
<title>Rollover with a Mouse Events</title>

<script type="text/javascript">
<!--
if(document.images){
var image1 = new Image(); // Preload an image
image1.src = "/images/html.gif";
var image2 = new Image(); // Preload second image
image2.src = "/images/http.gif";
}
//-->

NMC
JAVASCRIPT

</script>

</head>

<body>
<p>Move your mouse over the image to see the result</p>

<a href="#" onMouseOver="document.myImage.src=image2.src;"


onMouseOut="document.myImage.src=image1.src;">
<img name="myImage" src="/images/html.gif" />
</a>
</body>
</html>

MOVING IMAGES
<html>
<head>
<title>JavaScript Animation</title>
<script type="text/javascript">
<!--
var imgObj = null;
var animate ;
function init(){
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
}
function moveRight(){
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
animate = setTimeout(moveRight,20); // call moveRight in
20msec
}
function stop(){
clearTimeout(animate);
imgObj.style.left = '0px';
}
window.onload =init;

NMC
JAVASCRIPT

//-->
</script>
</head>
<body>
<form>
<img id="myImage" src="D:\Tulips11.jpg" />
<p>Click the buttons below to handle animation</p>
<input type="button" value="Start" onclick="moveRight();" />
<input type="button" value="Stop" onclick="stop();" />
</form>
</body>
</html>
TEXT-ONLY MENU SYSTEM
Text only menu system
<!DOCTYPE html>
<html>
<body>
<div style="background:yellow;border:1px solid #cccccc;padding: 10px;"
contextmenu="mymenu">
<p>Right-click inside this box to see the context menu!</p>
<menu type="context" id="mymenu">
<menuitem label="Refresh" onclick="window.location.reload();"
icon="ico_reload.png"></menuitem>
<menu label="Share on...">
<menuitem label="Twitter" icon="ico_twitter.png"
onclick="window.open('//twitter.com/intent/tweet?text=' + window.location.href);">
</menuitem>
<menuitem label="Facebook" icon="ico_facebook.png"
onclick="window.open('//facebook.com/sharer/sharer.php?u=' +
window.location.href);">
</menuitem>
</menu>
<menuitem label="Email This Page" onclick="window.location='mailto:?
body='+window.location.href;"></menuitem>
</menu>

FLOATING LOGOS

NMC
JAVASCRIPT

Floating logos
With the help of this script you can put up your logo on your website in such a way
that it floats on the page in any particular location that can be set.

//FLOATING LOGOS
<html>
<head>
<script language=javascript src="logo.js">
</script>
</head>
<body onLoad=Init()>
<div id="lay()" style="visibility: visible;
position: absolute; width:95%">
<!--Your Content Here-->
</div>

<div id="lay10"
style="visibility: visible;
position: absolute;
font-size: 20pt;
background: aquamarine;
color: purple;
text-align: center;
left: 5px;
top: 5px;
width: 256px;
height: 64px;">
<p>LOGO</p>
</div>
function init()
{
setup();
positionLogo();
}
</body>
</html>

FORM VALIDATION

NMC
JAVASCRIPT

//FORM VALIDATION
//DATE 4/2/19
<html>
<head>
<script language="javascript">
function validate()
{
var method=document.forms[0].method;
var action=document.forms[0].action;
var value=document.forms[0].elements[0].value;
if(value!="Mary")
{
document.forms[0].reset();
}
else
{
alert("Hi Mary!!");
}
}
</script>
</head>
<body>
<form method="post">
<input type="text" id="user" size="32"/>
<input type="submit" value="press me!"
onClick="validate()"/>
</form>
</body>
</html>

NMC

You might also like