SlideShare a Scribd company logo
MCA 202 Section B Notes
JavaScript
JavaScript is a lightweight, interpreted programming language. It is designed for creating
network-centric applications. It is complimentary to and integrated with Java. JavaScript is very
easy to implement because it is integrated with HTML. It is open and cross-platform.
<html>
<body>
<script language="javascript" type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
Client-side JavaScript
Client-side JavaScript is the most common form of the language. The script should be included
in or referenced by an HTML document for the code to be interpreted by the browser.
It means that a web page need not be a static HTML, but can include programs that interact with
the user, control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI server-
side scripts. For example, you might use JavaScript to check if the user has entered a valid e-
mail address in a form field.
The JavaScript code is executed when the user submits the form, and only if all the entries are
valid, they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and
other actions that the user initiates explicitly or implicitly.
Advantages ofJavaScript
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.
MCA 202 Section B Notes
 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 ofJavaScript
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.
Once again, JavaScript is a lightweight, interpreted programming language that allows you to
build interactivity into otherwise static HTML pages.
JavaScript 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 alerts the browser program to start interpreting all the text between these tags
as a script. A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>
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.
MCA 202 Section B Notes
 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>
JavaScript -Placement in HTMLFile
There is a flexibility given to include JavaScript code anywhere in an HTML document.
However the most preferred ways to include JavaScript in an HTML file are as follows −
 Script in <head>...</head> section.
 Script in <body>...</body> section.
 Script in <body>...</body> and <head>...</head> sections.
 Script in an external file and then include in <head>...</head> section.
In the following section, we will see how we can place JavaScript in an HTML file in different
ways.
JavaScript in<head>...</head> section
If you want to have a script run on some event, such as when a user clicks somewhere, then you
will place that script in the head as follows −
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
MCA 202 Section B Notes
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
JavaScript in<body>...</body> section
If you need a script to run as the page loads so that the script generates content in the page, then
the script goes in the <body> portion of the document. In this case, you would not have any
function defined using JavaScript. Take a look at the following code.
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
JavaScript Datatypes
One of the most fundamental characteristics of a programming language is the set of data types
it supports. These are the type of values that can be represented and manipulated in a
programming language.
JavaScript allows you to work with three primitive data types −
MCA 202 Section B Notes
 Numbers, eg. 123, 120.50 etc.
 Strings of text e.g. "This text string" etc.
 Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which defines only a
single value. In addition to these primitive data types, JavaScript supports a composite data type
known as object. We will cover objects in detail in a separate chapter.
JavaScript Variables
Like many other programming languages, JavaScript has variables. Variables can be thought of
as named containers. You can place data into these containers and then refer to the data simply
by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared
with the var keyword as follows.
<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>
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. Form validation generally performs two functions.
 Basic Validation − First of all, the form must be checked to make sure all the mandatory
fields are filled in. It would require just a loop through each field in the form and check
for data.
MCA 202 Section B Notes
 Data Format Validation − Secondly, the data that is entered must be checked for
correct form and value. Your code must include appropriate logic to test correctness of
data.
Example
We will take an example to understand the process of validation. Here is a simple form in html
format.
<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>
MCA 202 Section B Notes
</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>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
The HTML DOM (Document Object Model)
MCA 202 Section B Notes
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
What is the DOM?
The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that
allows programs and scripts to dynamically access and update the content, structure, and style
of a document."
The W3C DOM standard is separated into 3 different parts:
 Core DOM - standard model for all document types
 XML DOM - standard model for XML documents
 HTML DOM - standard model for HTML documents
MCA 202 Section B Notes
What is the HTML DOM?
The HTML DOM is a standard object model and programming interface for HTML. It
defines:
 The HTML elements as objects
 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements
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.
The DOM Programming Interface
The HTML DOM can be accessed with JavaScript (and with other programming languages).
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
<html>
<body>
<p id="demo"> BCA 6th</p>
<p id="123"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
The getElementById Method
The most common way to access an HTML element is to use the id of the element.
MCA 202 Section B Notes
In the example above the getElementById method used id="demo" to find the element.
The innerHTML Property
The easiest way to get the content of an element is by using the innerHTML property.
The innerHTML property is useful for getting or replacing the content of HTML elements.
The innerHTML property can be used to get or change any HTML element, including <html>
and <body>.
What is an Operator?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is
called the operator. JavaScript supports the following types of operators.
 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
Sr.No. Operator & 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
MCA 202 Section B Notes
5
% (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0
6
++ (Increment)
Increases an integer value by one
Ex: A++ will give 11
7
-- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9
Example:
<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;
MCA 202 Section B Notes
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>
JavaScript If…else
JavaScript supports conditional statements which are used to perform different actions based on
different conditions. Here we will explain the if..else statement.
Flow Chart of if-else
The following flow chart shows how the if-else statement works.
MCA 202 Section B Notes
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:
<html>
<body>
<script type = "text/javascript">
<!--
var age = 20;
MCA 202 Section B Notes
if( age > 18 ) {
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
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
}
Example:
<html>
<body>
<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>
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.
MCA 202 Section B Notes
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
}
Example:
<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>
you can use a switch statement which handles exactly this situation, and it does so more
efficiently than repeated if...else if statements.
Flow Chart
The following flow chart explains a switch-case statement works.
MCA 202 Section B Notes
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
<html>
<body>
MCA 202 Section B Notes
<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>
The while Loop
The most basic loop in JavaScript is the while loop which would be discussed in this chapter.
The purpose of a while loop is to execute a statement or code block repeatedly as long as an
expression is true. Once the expression becomes false, the loop terminates.
Flow Chart
The flow chart of while loop looks as follows −
MCA 202 Section B Notes
Syntax
The syntax of while loop in JavaScript is as follows −
while (expression) {
Statement(s) to be executed if expression is true
}
Example
<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;
document.write("Starting Loop ");
while (count < 10) {
document.write("Current Count : " + count + "<br />");
count++;
}
MCA 202 Section B Notes
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
The do...while Loop
The do...while loop is similar to the while loop except that the condition check happens at the
end of the loop. This means that the loop will always be executed at least once, even if the
condition is false.
Flow Chart
The flow chart of a do-while loop would be as follows −
Syntax
The syntax for do-while loop in JavaScript is as follows −
do {
Statement(s) to be executed;
} while (expression);
MCA 202 Section B Notes
Example
<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
do {
document.write("Current Count : " + count + "<br />");
count++;
}
while (count < 5);
document.write ("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
The 'for' loop is the most compact form of looping. It includes the following three important
parts −
 The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.
 The test statement which will test if a given condition is true or not. If the condition is
true, then the code given inside the loop will be executed, otherwise the control will come
out of the loop.
 The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
Flow Chart
The flow chart of a for loop in JavaScript would be as follows −
MCA 202 Section B Notes
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
}
<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>
Function Definition
MCA 202 Section B Notes
Before we use a function, we need to define it. The most common way to define a function in
JavaScript is by using the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded by curly braces.
Syntax
The basic syntax is shown here.
<script type = "text/javascript">
<!--
function functionname(parameter-list) {
statements
}
//-->
</script>
Example
<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>
What is an 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.
MCA 202 Section B Notes
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.
Please go through this small tutorial for a better understanding HTML Event Reference. Here we
will see a few examples to understand a relation between Event and JavaScript –
Here is a list of some common HTML events:
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page
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
<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>
MCA 202 Section B Notes
</html>
Form validation
<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
<!--
// Form validation code will come here.
function validate() {
if( document.myForm.Name.value == "" ) {
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" ) {
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" || isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 ) {
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" ) {
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>
<script type = "text/javascript">
<!--
function validateEmail() {
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 )) {
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
MCA 202 Section B Notes
return false;
}
return( true );
}
//-->
</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>
</td>
</tr>
<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>
</table>
MCA 202 Section B Notes
</form>
</body>
</html>
JavaScript Comments
Single Line Comments
Single line comments start with //.
Any text between // and the end of the line will be ignored by JavaScript (will not be executed).
This example uses a single-line comment before each code line:
Example
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
This example uses a multi-line comment (a comment block) to explain the code:
Example
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
JS array Methods
Tostring()
MCA 202 Section B Notes
The JavaScript method toString() converts an array to a string of (comma separated) array
values.
Example
var fruits= ["Banana","Orange","Apple","Mango"];
document.getElementById("demo").innerHTML= fruits.toString();
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array Methods</h2>
<h2>toString()</h2>
<p>The toString() method returns an array as a comma separated string:</p>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
</script>
</body>
</html>
Join()
The join() method also joins all array elements into a string.
It behaves just like toString(), but in addition you can specify the separator:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array Methods</h2>
<h2>join()</h2>
MCA 202 Section B Notes
<p>The join() method joins array elements into a string.</p>
<p>It this example we have used " * " as a separator between the elements:</p>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
</script>
</body>
</html>
JavaScript Validation API
Constraint Validation DOM Methods
Property Description
checkValidity() Returns true if an input element contains valid data.
setCustomValidity() Sets the validationMessage property of an input element.
<!DOCTYPE html>
<html>
<body>
<p>Enter a number and click OK:</p>
<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>
<p>If the number is less than 100 or greater than 300, an error message will be displayed.</p>
<p id="demo"></p>
<script>
function myFunction() {
MCA 202 Section B Notes
var inpObj = document.getElementById("id1");
if (!inpObj.checkValidity()) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
} else {
document.getElementById("demo").innerHTML = "Input OK";
}
}
</script>
</body>
</html>

More Related Content

What's hot

SharePoint 2010 Web Standards & Accessibility
SharePoint 2010 Web Standards & AccessibilitySharePoint 2010 Web Standards & Accessibility
SharePoint 2010 Web Standards & Accessibility
Mavention
 
Internet programming lecture 1
Internet programming lecture 1Internet programming lecture 1
Internet programming lecture 1
Mohammed Hussein
 
internet programming and java notes 5th sem mca
internet programming and java notes 5th sem mcainternet programming and java notes 5th sem mca
internet programming and java notes 5th sem mca
Renu Thakur
 
[DSBW Spring 2009] Unit 06: Conallen's Web Application Extension for UML (WAE2)
[DSBW Spring 2009] Unit 06: Conallen's Web Application Extension for UML (WAE2)[DSBW Spring 2009] Unit 06: Conallen's Web Application Extension for UML (WAE2)
[DSBW Spring 2009] Unit 06: Conallen's Web Application Extension for UML (WAE2)
Carles Farré
 
webservices overview
webservices overviewwebservices overview
webservices overview
elliando dias
 
Rutgers - FrontPage 98 (Advanced)
Rutgers - FrontPage 98 (Advanced)Rutgers - FrontPage 98 (Advanced)
Rutgers - FrontPage 98 (Advanced)
Michael Dobe, Ph.D.
 
Ultimate Skills Checklist for Your First Front-End Developer Job
Ultimate Skills Checklist for Your First Front-End Developer JobUltimate Skills Checklist for Your First Front-End Developer Job
Ultimate Skills Checklist for Your First Front-End Developer Job
Brenna Van Norman
 

What's hot (20)

SharePoint 2010 Web Standards & Accessibility
SharePoint 2010 Web Standards & AccessibilitySharePoint 2010 Web Standards & Accessibility
SharePoint 2010 Web Standards & Accessibility
 
Internet programming lecture 1
Internet programming lecture 1Internet programming lecture 1
Internet programming lecture 1
 
internet programming and java notes 5th sem mca
internet programming and java notes 5th sem mcainternet programming and java notes 5th sem mca
internet programming and java notes 5th sem mca
 
MVC Training Part 1
MVC Training Part 1MVC Training Part 1
MVC Training Part 1
 
0 csc 3311 slide internet programming
0 csc 3311 slide internet programming0 csc 3311 slide internet programming
0 csc 3311 slide internet programming
 
[DSBW Spring 2009] Unit 06: Conallen's Web Application Extension for UML (WAE2)
[DSBW Spring 2009] Unit 06: Conallen's Web Application Extension for UML (WAE2)[DSBW Spring 2009] Unit 06: Conallen's Web Application Extension for UML (WAE2)
[DSBW Spring 2009] Unit 06: Conallen's Web Application Extension for UML (WAE2)
 
Web 2.0
Web 2.0Web 2.0
Web 2.0
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
 
Ruby on Rails: Building Web Applications Is Fun Again!
Ruby on Rails: Building Web Applications Is Fun Again!Ruby on Rails: Building Web Applications Is Fun Again!
Ruby on Rails: Building Web Applications Is Fun Again!
 
webservices overview
webservices overviewwebservices overview
webservices overview
 
Rutgers - FrontPage 98 (Advanced)
Rutgers - FrontPage 98 (Advanced)Rutgers - FrontPage 98 (Advanced)
Rutgers - FrontPage 98 (Advanced)
 
06 Javascript
06 Javascript06 Javascript
06 Javascript
 
CS6501 - Internet programming
CS6501 - Internet programming   CS6501 - Internet programming
CS6501 - Internet programming
 
Front End Development | Introduction
Front End Development | IntroductionFront End Development | Introduction
Front End Development | Introduction
 
Web 2.0
Web 2.0Web 2.0
Web 2.0
 
Java script
Java scriptJava script
Java script
 
Overview of ASP.Net by software outsourcing company india
Overview of ASP.Net by software outsourcing company indiaOverview of ASP.Net by software outsourcing company india
Overview of ASP.Net by software outsourcing company india
 
Asp net
Asp netAsp net
Asp net
 
Ultimate Skills Checklist for Your First Front-End Developer Job
Ultimate Skills Checklist for Your First Front-End Developer JobUltimate Skills Checklist for Your First Front-End Developer Job
Ultimate Skills Checklist for Your First Front-End Developer Job
 
Web Development
Web DevelopmentWeb Development
Web Development
 

Similar to JavaScript

Iwt note(module 2)
Iwt note(module 2)Iwt note(module 2)
Iwt note(module 2)
SANTOSH RATH
 

Similar to JavaScript (20)

JS BASICS JAVA SCRIPT SCRIPTING
JS BASICS JAVA SCRIPT SCRIPTINGJS BASICS JAVA SCRIPT SCRIPTING
JS BASICS JAVA SCRIPT SCRIPTING
 
CHAPTER 3 JS (1).pptx
CHAPTER 3  JS (1).pptxCHAPTER 3  JS (1).pptx
CHAPTER 3 JS (1).pptx
 
JAVA SCRIPT
JAVA SCRIPTJAVA SCRIPT
JAVA SCRIPT
 
Basic Java script handouts for students
Basic Java script handouts for students Basic Java script handouts for students
Basic Java script handouts for students
 
MCA-202-W4-L1.pptx
MCA-202-W4-L1.pptxMCA-202-W4-L1.pptx
MCA-202-W4-L1.pptx
 
Javascript tutorial
Javascript tutorialJavascript tutorial
Javascript tutorial
 
web designing course bangalore
web designing course bangaloreweb designing course bangalore
web designing course bangalore
 
Session vii(java scriptbasics)
Session vii(java scriptbasics)Session vii(java scriptbasics)
Session vii(java scriptbasics)
 
Overview of PHP and MYSQL
Overview of PHP and MYSQLOverview of PHP and MYSQL
Overview of PHP and MYSQL
 
Introduction to Web Technologies PPT.pptx
Introduction to Web Technologies PPT.pptxIntroduction to Web Technologies PPT.pptx
Introduction to Web Technologies PPT.pptx
 
Iwt note(module 2)
Iwt note(module 2)Iwt note(module 2)
Iwt note(module 2)
 
Final Java-script.pptx
Final Java-script.pptxFinal Java-script.pptx
Final Java-script.pptx
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 
Javascript - Ebook (A Quick Guide)
Javascript - Ebook (A Quick Guide)Javascript - Ebook (A Quick Guide)
Javascript - Ebook (A Quick Guide)
 
Presentation about html5 css3
Presentation about html5 css3Presentation about html5 css3
Presentation about html5 css3
 
Javascript session 1
Javascript session 1Javascript session 1
Javascript session 1
 
2javascript web programming with JAVA script
2javascript web programming with JAVA script2javascript web programming with JAVA script
2javascript web programming with JAVA script
 
web devs ppt.ppsx
web devs ppt.ppsxweb devs ppt.ppsx
web devs ppt.ppsx
 
Html5 deciphered - designing concepts part 1
Html5 deciphered - designing concepts part 1Html5 deciphered - designing concepts part 1
Html5 deciphered - designing concepts part 1
 
PPT on javascript ajax and css and some points related to server
PPT on javascript ajax and css and some points related to serverPPT on javascript ajax and css and some points related to server
PPT on javascript ajax and css and some points related to server
 

More from Gulbir Chaudhary (7)

Steps for Developing Website
Steps for Developing WebsiteSteps for Developing Website
Steps for Developing Website
 
Five rules of web designing
Five rules of web designingFive rules of web designing
Five rules of web designing
 
Basic Principles of website designing
Basic Principles of website designing Basic Principles of website designing
Basic Principles of website designing
 
Introduction of internet
Introduction of internetIntroduction of internet
Introduction of internet
 
Ip v4
Ip v4Ip v4
Ip v4
 
Http vs https
Http vs httpsHttp vs https
Http vs https
 
Practicals it
Practicals itPracticals it
Practicals it
 

Recently uploaded

Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.pdf
Kamal Acharya
 
Hall booking system project report .pdf
Hall booking system project report  .pdfHall booking system project report  .pdf
Hall booking system project report .pdf
Kamal Acharya
 
Laundry management system project report.pdf
Laundry management system project report.pdfLaundry management system project report.pdf
Laundry management system project report.pdf
Kamal Acharya
 

Recently uploaded (20)

KIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and Clustering
KIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and ClusteringKIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and Clustering
KIT-601 Lecture Notes-UNIT-4.pdf Frequent Itemsets and Clustering
 
Construction method of steel structure space frame .pptx
Construction method of steel structure space frame .pptxConstruction method of steel structure space frame .pptx
Construction method of steel structure space frame .pptx
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
 
Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.pdf
 
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdfA CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
 
Arduino based vehicle speed tracker project
Arduino based vehicle speed tracker projectArduino based vehicle speed tracker project
Arduino based vehicle speed tracker project
 
Explosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdfExplosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdf
 
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
 
Peek implant persentation - Copy (1).pdf
Peek implant persentation - Copy (1).pdfPeek implant persentation - Copy (1).pdf
Peek implant persentation - Copy (1).pdf
 
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWINGBRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
Hall booking system project report .pdf
Hall booking system project report  .pdfHall booking system project report  .pdf
Hall booking system project report .pdf
 
Toll tax management system project report..pdf
Toll tax management system project report..pdfToll tax management system project report..pdf
Toll tax management system project report..pdf
 
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
 
Laundry management system project report.pdf
Laundry management system project report.pdfLaundry management system project report.pdf
Laundry management system project report.pdf
 
İTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering WorkshopİTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering Workshop
 
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
 
Pharmacy management system project report..pdf
Pharmacy management system project report..pdfPharmacy management system project report..pdf
Pharmacy management system project report..pdf
 
Scaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltageScaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltage
 
KIT-601 Lecture Notes-UNIT-3.pdf Mining Data Stream
KIT-601 Lecture Notes-UNIT-3.pdf Mining Data StreamKIT-601 Lecture Notes-UNIT-3.pdf Mining Data Stream
KIT-601 Lecture Notes-UNIT-3.pdf Mining Data Stream
 

JavaScript

  • 1. MCA 202 Section B Notes JavaScript JavaScript is a lightweight, interpreted programming language. It is designed for creating network-centric applications. It is complimentary to and integrated with Java. JavaScript is very easy to implement because it is integrated with HTML. It is open and cross-platform. <html> <body> <script language="javascript" type="text/javascript"> document.write("Hello World!") </script> </body> </html> Client-side JavaScript Client-side JavaScript is the most common form of the language. The script should be included in or referenced by an HTML document for the code to be interpreted by the browser. It means that a web page need not be a static HTML, but can include programs that interact with the user, control the browser, and dynamically create HTML content. The JavaScript client-side mechanism provides many advantages over traditional CGI server- side scripts. For example, you might use JavaScript to check if the user has entered a valid e- mail address in a form field. The JavaScript code is executed when the user submits the form, and only if all the entries are valid, they would be submitted to the Web Server. JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other actions that the user initiates explicitly or implicitly. Advantages ofJavaScript 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.
  • 2. MCA 202 Section B Notes  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 ofJavaScript 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. Once again, JavaScript is a lightweight, interpreted programming language that allows you to build interactivity into otherwise static HTML pages. JavaScript 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 alerts the browser program to start interpreting all the text between these tags as a script. A simple syntax of your JavaScript will appear as follows. <script ...> JavaScript code </script> 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.
  • 3. MCA 202 Section B Notes  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> JavaScript -Placement in HTMLFile There is a flexibility given to include JavaScript code anywhere in an HTML document. However the most preferred ways to include JavaScript in an HTML file are as follows −  Script in <head>...</head> section.  Script in <body>...</body> section.  Script in <body>...</body> and <head>...</head> sections.  Script in an external file and then include in <head>...</head> section. In the following section, we will see how we can place JavaScript in an HTML file in different ways. JavaScript in<head>...</head> section If you want to have a script run on some event, such as when a user clicks somewhere, then you will place that script in the head as follows − <html> <head> <script type="text/javascript"> <!-- function sayHello() { alert("Hello World") } //-->
  • 4. MCA 202 Section B Notes </script> </head> <body> <input type="button" onclick="sayHello()" value="Say Hello" /> </body> </html> JavaScript in<body>...</body> section If you need a script to run as the page loads so that the script generates content in the page, then the script goes in the <body> portion of the document. In this case, you would not have any function defined using JavaScript. Take a look at the following code. <html> <head> </head> <body> <script type="text/javascript"> <!-- document.write("Hello World") //--> </script> <p>This is web page body </p> </body> </html> JavaScript Datatypes One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language. JavaScript allows you to work with three primitive data types −
  • 5. MCA 202 Section B Notes  Numbers, eg. 123, 120.50 etc.  Strings of text e.g. "This text string" etc.  Boolean e.g. true or false. JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value. In addition to these primitive data types, JavaScript supports a composite data type known as object. We will cover objects in detail in a separate chapter. JavaScript Variables Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container. Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows. <script type="text/javascript"> <!-- var money; var name; //--> </script> 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. Form validation generally performs two functions.  Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data.
  • 6. MCA 202 Section B Notes  Data Format Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data. Example We will take an example to understand the process of validation. Here is a simple form in html format. <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>
  • 7. MCA 202 Section B Notes </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> </td> </tr> <tr> <td align="right"></td> <td><input type="submit" value="Submit" /></td> </tr> </table> </form> </body> </html> The HTML DOM (Document Object Model)
  • 8. MCA 202 Section B Notes 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 What is the DOM? The DOM is a W3C (World Wide Web Consortium) standard. The DOM defines a standard for accessing documents: "The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document." The W3C DOM standard is separated into 3 different parts:  Core DOM - standard model for all document types  XML DOM - standard model for XML documents  HTML DOM - standard model for HTML documents
  • 9. MCA 202 Section B Notes What is the HTML DOM? The HTML DOM is a standard object model and programming interface for HTML. It defines:  The HTML elements as objects  The properties of all HTML elements  The methods to access all HTML elements  The events for all HTML elements 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. The DOM Programming Interface The HTML DOM can be accessed with JavaScript (and with other programming languages). 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 <html> <body> <p id="demo"> BCA 6th</p> <p id="123"></p> <script> document.getElementById("demo").innerHTML = "Hello World!"; </script> </body> </html> The getElementById Method The most common way to access an HTML element is to use the id of the element.
  • 10. MCA 202 Section B Notes In the example above the getElementById method used id="demo" to find the element. The innerHTML Property The easiest way to get the content of an element is by using the innerHTML property. The innerHTML property is useful for getting or replacing the content of HTML elements. The innerHTML property can be used to get or change any HTML element, including <html> and <body>. What is an Operator? Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is called the operator. JavaScript supports the following types of operators.  Arithmetic Operators  Comparison Operators  Logical (or Relational) Operators  Assignment Operators  Conditional (or ternary) Operators Sr.No. Operator & 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
  • 11. MCA 202 Section B Notes 5 % (Modulus) Outputs the remainder of an integer division Ex: B % A will give 0 6 ++ (Increment) Increases an integer value by one Ex: A++ will give 11 7 -- (Decrement) Decreases an integer value by one Ex: A-- will give 9 Example: <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;
  • 12. MCA 202 Section B Notes 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> JavaScript If…else JavaScript supports conditional statements which are used to perform different actions based on different conditions. Here we will explain the if..else statement. Flow Chart of if-else The following flow chart shows how the if-else statement works.
  • 13. MCA 202 Section B Notes 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: <html> <body> <script type = "text/javascript"> <!-- var age = 20;
  • 14. MCA 202 Section B Notes if( age > 18 ) { document.write("<b>Qualifies for driving</b>"); } //--> </script> <p>Set the variable to different value and then try...</p> </body> </html> 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 } Example: <html> <body> <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> 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.
  • 15. MCA 202 Section B Notes 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 } Example: <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> you can use a switch statement which handles exactly this situation, and it does so more efficiently than repeated if...else if statements. Flow Chart The following flow chart explains a switch-case statement works.
  • 16. MCA 202 Section B Notes 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 <html> <body>
  • 17. MCA 202 Section B Notes <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> The while Loop The most basic loop in JavaScript is the while loop which would be discussed in this chapter. The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates. Flow Chart The flow chart of while loop looks as follows −
  • 18. MCA 202 Section B Notes Syntax The syntax of while loop in JavaScript is as follows − while (expression) { Statement(s) to be executed if expression is true } Example <html> <body> <script type = "text/javascript"> <!-- var count = 0; document.write("Starting Loop "); while (count < 10) { document.write("Current Count : " + count + "<br />"); count++; }
  • 19. MCA 202 Section B Notes document.write("Loop stopped!"); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html> The do...while Loop The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false. Flow Chart The flow chart of a do-while loop would be as follows − Syntax The syntax for do-while loop in JavaScript is as follows − do { Statement(s) to be executed; } while (expression);
  • 20. MCA 202 Section B Notes Example <html> <body> <script type = "text/javascript"> <!-- var count = 0; document.write("Starting Loop" + "<br />"); do { document.write("Current Count : " + count + "<br />"); count++; } while (count < 5); document.write ("Loop stopped!"); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html> The 'for' loop is the most compact form of looping. It includes the following three important parts −  The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.  The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.  The iteration statement where you can increase or decrease your counter. You can put all the three parts in a single line separated by semicolons. Flow Chart The flow chart of a for loop in JavaScript would be as follows −
  • 21. MCA 202 Section B Notes 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 } <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> Function Definition
  • 22. MCA 202 Section B Notes Before we use a function, we need to define it. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces. Syntax The basic syntax is shown here. <script type = "text/javascript"> <!-- function functionname(parameter-list) { statements } //--> </script> Example <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> What is an 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.
  • 23. MCA 202 Section B Notes 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. Please go through this small tutorial for a better understanding HTML Event Reference. Here we will see a few examples to understand a relation between Event and JavaScript – Here is a list of some common HTML events: Event Description onchange An HTML element has been changed onclick The user clicks an HTML element onmouseover The user moves the mouse over an HTML element onmouseout The user moves the mouse away from an HTML element onkeydown The user pushes a keyboard key onload The browser has finished loading the page 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 <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>
  • 24. MCA 202 Section B Notes </html> Form validation <html> <head> <title>Form Validation</title> <script type = "text/javascript"> <!-- // Form validation code will come here. function validate() { if( document.myForm.Name.value == "" ) { alert( "Please provide your name!" ); document.myForm.Name.focus() ; return false; } if( document.myForm.EMail.value == "" ) { alert( "Please provide your Email!" ); document.myForm.EMail.focus() ; return false; } if( document.myForm.Zip.value == "" || isNaN( document.myForm.Zip.value ) || document.myForm.Zip.value.length != 5 ) { alert( "Please provide a zip in the format #####." ); document.myForm.Zip.focus() ; return false; } if( document.myForm.Country.value == "-1" ) { alert( "Please provide your country!" ); return false; } return( true ); } //--> </script> <script type = "text/javascript"> <!-- function validateEmail() { var emailID = document.myForm.EMail.value; atpos = emailID.indexOf("@"); dotpos = emailID.lastIndexOf("."); if (atpos < 1 || ( dotpos - atpos < 2 )) { alert("Please enter correct email ID") document.myForm.EMail.focus() ;
  • 25. MCA 202 Section B Notes return false; } return( true ); } //--> </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> </td> </tr> <tr> <td align = "right"></td> <td><input type = "submit" value = "Submit" /></td> </tr> </table>
  • 26. MCA 202 Section B Notes </form> </body> </html> JavaScript Comments Single Line Comments Single line comments start with //. Any text between // and the end of the line will be ignored by JavaScript (will not be executed). This example uses a single-line comment before each code line: Example // Change heading: document.getElementById("myH").innerHTML = "My First Page"; // Change paragraph: document.getElementById("myP").innerHTML = "My first paragraph."; Multi-line Comments Multi-line comments start with /* and end with */. Any text between /* and */ will be ignored by JavaScript. This example uses a multi-line comment (a comment block) to explain the code: Example /* The code below will change the heading with id = "myH" and the paragraph with id = "myP" in my web page: */ document.getElementById("myH").innerHTML = "My First Page"; document.getElementById("myP").innerHTML = "My first paragraph."; JS array Methods Tostring()
  • 27. MCA 202 Section B Notes The JavaScript method toString() converts an array to a string of (comma separated) array values. Example var fruits= ["Banana","Orange","Apple","Mango"]; document.getElementById("demo").innerHTML= fruits.toString(); <!DOCTYPE html> <html> <body> <h2>JavaScript Array Methods</h2> <h2>toString()</h2> <p>The toString() method returns an array as a comma separated string:</p> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.toString(); </script> </body> </html> Join() The join() method also joins all array elements into a string. It behaves just like toString(), but in addition you can specify the separator: <!DOCTYPE html> <html> <body> <h2>JavaScript Array Methods</h2> <h2>join()</h2>
  • 28. MCA 202 Section B Notes <p>The join() method joins array elements into a string.</p> <p>It this example we have used " * " as a separator between the elements:</p> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.join(" * "); </script> </body> </html> JavaScript Validation API Constraint Validation DOM Methods Property Description checkValidity() Returns true if an input element contains valid data. setCustomValidity() Sets the validationMessage property of an input element. <!DOCTYPE html> <html> <body> <p>Enter a number and click OK:</p> <input id="id1" type="number" min="100" max="300" required> <button onclick="myFunction()">OK</button> <p>If the number is less than 100 or greater than 300, an error message will be displayed.</p> <p id="demo"></p> <script> function myFunction() {
  • 29. MCA 202 Section B Notes var inpObj = document.getElementById("id1"); if (!inpObj.checkValidity()) { document.getElementById("demo").innerHTML = inpObj.validationMessage; } else { document.getElementById("demo").innerHTML = "Input OK"; } } </script> </body> </html>