BCA Javascript
BCA Javascript
JavaScript
<html>
<body>
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 of JavaScript
The merits of using JavaScript are −
Less server interaction − You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
Immediate feedback to the visitors − They don't have to wait for a page reload to see if
they have forgotten to enter something.
BCA 302 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 of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the following
important features −
Client-side JavaScript does not allow the reading or writing of files. This has been kept
for security reason.
JavaScript cannot be used for networking applications because there is no such support
available.
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>
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.
BCA 302 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".
JavaScript code
</script>
In the following section, we will see how we can place JavaScript in an HTML file in different
ways.
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
//-->
BCA 302 Section B Notes
</script>
</head>
<body>
</body>
</html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
</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 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 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.
BCA 302 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">
<!--
//-->
</script>
</head>
<body>
<tr>
<td align="right">Name</td>
</tr>
<tr>
<td align="right">EMail</td>
</tr>
<tr>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
</tr>
</table>
</form>
</body>
</html>
When a web page is loaded, the browser creates a Document Object Model of the page
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
"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 HTML DOM is a standard object model and programming interface for HTML. It
defines:
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 HTML DOM can be accessed with JavaScript (and with other programming languages).
A property is a value that you can get or set (like changing the content of an HTML element).
Example
<html>
<body>
</body>
</html>
The most common way to access an HTML element is to use the id of the element.
BCA 302 Section B Notes
In the example above the getElementById method used id="demo" to find the element.
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
% (Modulus)
Example:
<html>
<body>
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;
BCA 302 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>
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.
The following flow chart shows how the if-else statement works.
BCA 302 Section B Notes
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
if (expression) {
Statement(s) to be executed if expression is true
}
Example:
<html>
<body>
<script type = "text/javascript">
<!--
var age = 20;
BCA 302 Section B Notes
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;
The if...else if... statement is an advanced form of if…else that allows JavaScript to make a
correct decision out of several conditions.
BCA 302 Section B Notes
Syntax
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
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;
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.
Example
<html>
<body>
BCA 302 Section B Notes
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
Syntax
while (expression) {
Statement(s) to be executed if expression is true
}
Example
<html>
<body>
document.write("Loop stopped!");
//-->
</script>
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
Syntax
do {
Statement(s) to be executed;
} while (expression);
BCA 302 Section B Notes
Example
<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;
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
Syntax
Function Definition
BCA 302 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
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.
BCA 302 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 –
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
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>
BCA 302 Section B Notes
</html>
Form validation
<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
<!--
// Form validation code will come here.
function validate() {
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>
BCA 302 Section B Notes
</form>
</body>
</html>
JavaScript Comments
Any text between // and the end of the line will be ignored by JavaScript (will not be executed).
Example
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
Multi-line Comments
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()
BCA 302 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>toString()</h2>
<p id="demo"></p>
<script>
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>join()</h2>
BCA 302 Section B Notes
<p>It this example we have used " * " as a separator between the elements:</p>
<p id="demo"></p>
<script>
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<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() {
BCA 302 Section B Notes
if (!inpObj.checkValidity()) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
} else {
</script>
</body>
</html>