Chapter 4 - JavaScript
Chapter 4 - JavaScript
Client-side validation,
Dynamic drop-down menus,
Displaying date and time,
Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog
box and prompt dialog box),
Displaying clocks etc.
JavaScript Example
JavaScript example is easy to code. Let’s create the first JavaScript example.
<script type="text/javascript">
[Link]("Hello World");
</script>
The script tag specifies that we are using JavaScript.
The text/javascript is the content type that provides information to the browser about the
data.
The [Link]() function is used to display dynamic content through JavaScript. We
will learn about document object in detail later.
<script type="text/javascript">
alert(" Welcome to JavaScript ");
</script>
</body>
</html>
2. JavaScript Example: code between the head tag
Let’s see the same example of displaying alert dialog box of JavaScript that is contained inside
the head tag. In this example, we are creating a function msg(). To create function in JavaScript,
you need to write function with function_name as given below.
To call function, you need to work on event. Here we are using onclick event to call msg()
function.
<html>
<head>
<script type="text/javascript">
function msg() {
alert("You clicked a button");
}
</script>
</head>
<body>
<p> Welcome to JavaScript </p>
<form>
<input type="button" value="Click Here" onclick="msg()"/>
</form>
</body>
</html>
We can create external JavaScript file and embed it in many html pages. It provides code re-
usability because single JavaScript file can be used in several html pages.
An external JavaScript file must be saved by .js extension. It is recommended to embed all
JavaScript files into a single file. It increases the speed of the webpage.
Let's create an external JavaScript file that prints Hello World in an alert dialog box.
[Link]
function msg() {
alert("Hello World ");
}
Let's include the JavaScript file into html page. It calls the JavaScript function on button click.
[Link]
<html>
<head>
<script type="text/javascript" src="[Link]">
</script>
</head>
<body>
<p> Welcome to JavaScript </p>
<form>
<input type="button" value="Click" onclick="msg()"/>
</form>
</body>
</html>
Using innerHTML
To access an HTML element, JavaScript can use the [Link](id)
method. The id attribute defines the HTML element. The innerHTML property defines the
HTML content.
Example:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML=5+6;
</script>
<p>My Second Paragraph</p>
</body>
</html>
Using [Link]()
<!DOCTYPE html> Output:
<html>
<body>
<h1> My First Web Page </h1>
<p> My first paragraph. </p>
<script>
[Link](5 + 6);
</script>
</body>
</html>
Using [Link]()
You can use an alert box to display data.
Example
<!DOCTYPE html>
<html>
<body>
<h1> My First Web Page</h1>
<p> My first paragraph.</p>
<script>
[Link](5 + 6);
</script>
</body>
</html>
You can skip the window keyword.
In JavaScript, the window object is the global scope object, that means that variables, properties,
and methods by default belong to the window object. This also means that specifying the
window keyword is optional:
Using [Link]()
For debugging purposes, you can call the [Link]() method in the browser to display
data.
Example
<!DOCTYPE html>
<html>
<body>
<script>
[Link](5 + 6);
</script>
</body>
</html>
a = 5; b = 6; c = a + b;
JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.
The purpose of code blocks is to define statements to be executed together.
One place you will find statements grouped together in blocks, is in JavaScript functions:
function myFunction() {
[Link]("demo1").innerHTML = "Hello Dolly!";
[Link]("demo2").innerHTML = "How are you?";
}
JavaScript Literals
The two most important syntax rules for fixed values are:
1. Numbers are written with or without decimals: 10.50 1001
2. Strings are text, written within double or single quotes: "John Doe" 'John Doe'
JavaScript Variables
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be
performed.
JavaScript keywords are used to identify actions to be performed.
The let keyword tells the browser to create variables:
let x, y;
x = 5 + 6;
y = x * 10;
The var keyword also tells the browser to create variables:
var x, y;
x = 5 + 6;
y = x * 10;
In these examples, using var or let will produce the same result.
Keyword Description
var Declares a variable
let Declares a block variable
const Declares a block constant
if Marks a block of statements to be executed on a condition
switch Marks a block of statements to be executed in different cases
for Marks a block of statements to be executed in a loop
function Declares a function
return Exits a function
try Implements error handling to a block of statements
JavaScript Comments
JavaScript comments can be used to explain JavaScript code, and to make it more readable.
JavaScript comments can also be used to prevent execution, when testing alternative code.
Not all JavaScript statements are "executed".
Code after double slashes // or between /* and */ is treated as a comment.
Comments are ignored, and will not be executed:
let x = 5; // I will be executed
// x = 6; I will NOT be executed
JavaScript Identifiers / Names
Historically, programmers have used different ways of joining multiple words into one variable
name.
Hyphens:
first-name, last-name, master-card, inter-city.
Hyphens are not allowed in JavaScript. They are reserved for subtractions.
Underscore:
first_name, last_name, master_card, inter_city.
Upper Camel Case (Pascal Case):
FirstName, LastName, MasterCard, InterCity.
Lower Camel Case:
JavaScript programmers tend to use camel case that starts with a lowercase letter:
firstName, lastName, masterCard, interCity.
The variable total is declared with the let keyword. This is a value that can be changed.
JavaScript variables can hold numbers like 100 and text values like "John Doe".
In programming, text values are called text strings.
JavaScript can handle many types of data, but for now, just think of numbers and strings.
Strings are written inside double or single quotes. Numbers are written without quotes.
If you put a number in quotes, it will be treated as a text string.
const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';
In computer programs, variables are often declared without a value. The value can be something
that has to be calculated, or something that will be provided later, like user input.
A variable declared without a value will have the value undefined.
The variable carName will have the value undefined after the execution of this statement:
let carName;
If you re-declare a JavaScript variable declared with var, it will not lose its value.
The variable carName will still have the value "Volvo" after the execution of these statements:
Example:
var carName = "Volvo";
var carName;
Note: You cannot re-declare a variable declared with let or const.
This will not work:
let carName = "Volvo";
let carName;
Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable names:
let $ = "Hello World";
let $$$ = 2;
let $myMoney = 5;
Using the dollar sign is not very common in JavaScript, but professional programmers often use
it as an alias for the main function in a JavaScript library.
In the JavaScript library jQuery, for instance, the main function $ is used to select HTML
elements. In jQuery $("p"); means "select all p elements".
The global method Number() converts a variable (or a value) into a number. A numeric string
(like "3.14") converts to a number (like 3.14). An empty string (like "") converts to 0. A non
numeric string (like "John") converts to NaN (Not a Number).
Example
These will convert:
Number("3.14") // returns 3.14
Number([Link]) // returns 3.141592653589793
Number(" ") // returns 0
Number("") // returns 0
These will not convert:
Number("99 88") // returns NaN
Number("John") // returns NaN
Number Methods
Method Description
Number() Returns a number, converted from its argument
parseFloat() Parses a string and returns a floating point number
parseInt() Parses a string and returns an integer
d = new Date();
[Link]() // returns 1404568027739
Converting Dates to Strings
Example
When JavaScript tries to operate on a "wrong" data type, it will try to convert the value to a
"right" type. The result is not always what you expect:
5 + null // returns 5 because null is converted to 0
"5" + null // returns "5null" because null is converted to "null"
"5" + 2 // returns "52" because 2 is converted to "2"
"5" - 2 // returns 3 because "5" is converted to 5
"5" * "2" // returns 10 because "5" and "2" are converted to 5 and 2
100 + 50
x=y x=y
=
x += y x=x+y
+=
x -= y x=x-y
-=
x *= y x=x*y
*=
x /= y x=x/y
/=
x %= y x=x%y
%=
x **= y x = x ** y
**=
Operator Description
== equal to
!= not equal
? ternary operator
|| logical or
! logical not
if … else
switch case
do while loop
while loop
for loop
If … else
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
<script type="text/javascript">
var age = 20;
if (age > 18) {
[Link]("<b>Qualifies for driving</b>");
}
</script>
If…else if…else
<script>
const time = new Date().getHours();
let greeting;
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
</script>
Switch case
The basic syntax of the 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.
Syntax:
switch (expression) {
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
Example
<script type="text/javascript">
var grade='A';
[Link]("Entering switch block<br/>");
switch (grade) {
case 'A': [Link]("Good job<br/>");
break;
case 'B': [Link]("Pretty good<br/>");
break;
case 'C': [Link]("Passed<br/>");
break;
case 'D': [Link]("Not so good<br/>");
break;
case 'F': [Link]("Failed<br/>");
break;
default: [Link]("Unknown grade<br/>")
}
[Link]("Exiting switch block");
</script>
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.
Syntax:
do {
Statement(s) to be executed;
} while (expression);
Example
<script type="text/javascript">
var count = 0;
[Link]("Starting Loop" + "<br/>");
do{
[Link]("Current Count : " + count + "<br/>");
count++;
}while (count < 0);
[Link]("Loop stopped!");
</script>
While Loop
The purpose of a while loop is to execute a statement or code block repeatedly as long as
expression is true. Once expression becomes false, the loop will be exited.
Syntax:
while (expression){
Statement(s) to be executed if expression is true
}
Example
<script type="text/javascript">
var count = 0;
[Link]("Starting Loop" + "<br/>");
while (count < 10){
[Link]("Current Count : " + count + "<br/>");
count++;
}
[Link]("Loop stopped!");
</script>
For Loop
The for loop is the most compact form of looping and 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 the given condition is true or not. If condition is true
then code given inside the loop will be executed otherwise loop will come out.
The iteration statement where you can increase or decrease your counter.
Syntax
Example
<script type="text/javascript">
var count;
[Link]("Starting Loop" + "<br/>");
for(count = 0; count < 10; count++){
[Link]("Current Count : " + count );
[Link]("<br/>");
}
[Link]("Loop stopped!");
</script>
Creating an Array
The following example also creates an Array, and assigns values to it.
const cars = new Array("Saab", "Volvo", "BMW");
With JavaScript, the full array can be accessed by referring to the array name.
Example
const cars = ["Saab", "Volvo", "BMW"];
[Link]("demo").innerHTML = cars;
Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.
But, JavaScript arrays are best described as arrays.
Arrays use numbers to access its "elements". In this example, person[0] returns John.
Array:
const person = ["John", "Doe", 46];
Objects use names to access its "members". In this example, [Link] returns John.
Object:
const person = {firstName:"John", lastName:"Doe", age:46};
The real strength of JavaScript arrays are the built-in array properties and methods:
[Link] // Returns the number of elements
[Link]() // Sorts the array
The length property of an array returns the length of an array (the number of array elements).
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = [Link];
The length property is always one more than the highest array index.
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[0];
Accessing the Last Array Element
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[[Link] - 1];
Looping Array Elements
One way to loop through an array, is using a for loop:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = [Link];
let text = "<ul>";
for (let i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
The easiest way to add a new element to an array is using the push() method.
Example
const fruits = ["Banana", "Orange", "Apple"];
[Link]("Lemon"); // Adds a new element (Lemon) to fruits
A JavaScript function is defined with the function keyword, followed by a name, followed
by parentheses ( ).
Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: { }
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after
the invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":
Example
Calculate the product of two numbers, and return the result:
let x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
The result in x will be:
12
<!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>
<script>
var x = myFunction(4, 3);
[Link]("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}
</script>
</body>
</html>
Why Functions?
You can reuse code: Define the code once, and use it many times. You can use the same code
many times with different arguments, to produce different results.
Example
Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
[Link]("demo").innerHTML = toCelsius(77);
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function to convert from Fahrenheit to
Celsius:</p>
<p id="demo"></p>
<script>
function toCelsius(f) {
return (5/9) * (f-32);
}
[Link]("demo").innerHTML = toCelsius(77);
</script>
</body>
</html>
Using the example above, toCelsius refers to the function object, and toCelsius() refers to
the function result.
Accessing a function without () will return the function object instead of the function result.
Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
[Link]("demo").innerHTML = toCelsius;
Local Variables
<html>
<body>
<button onclick="[Link]=Date()">The time is?</button>
<p>Click to display the date.</p>
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
[Link]("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
</script>
</body>
</html>
Output
Displaying Dates
JavaScript will (by default) output dates in full text string format.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>Using new Date()</h2>
<p>new Date() without arguments, creates a date object with the
current date and time:</p>
<p id="demo"></p>
<script>
const d = new Date();
[Link]("demo").innerHTML = d;
</script>
</body>
</html>
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).
In the DOM, all HTML elements are defined as objects.
The programming interface is the properties and methods of each object.
A property is a value that you can get or set (like changing the content of an HTML element).
A method is an action you can do (like add or deleting an HTML element).
Example
The following example changes the content (the innerHTML) of the <p> element with
id="demo":
<html>
<body>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
The most common way to access an HTML element is to use the id of the element.
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>.
Data validation is the process of ensuring that user input is clean, correct, and useful.
Typical validation tasks are:
Most often, the purpose of data validation is to ensure correct user input.
Validation can be defined by many different methods, and deployed in many different ways.
Server side validation is performed by a web server, after input has been sent to the server.
Client side validation is performed by a web browser, before input is sent to a web server.
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.
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.
JavaScript provides facility to validate the form on the client-side so data processing will be faster
than server-side validation. Most of the web developers prefer JavaScript form validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers and more
fields.
In this example, we are going to validate the name and password. The name can’t be empty and
password can’t be less than 6 characters long.
Here, we are validating the form on form submit. The user will not be forwarded to the next page
until given values are correct.
<script>
function validateform(){
var name=[Link];
var password=[Link];
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if([Link]<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="[Link]"
onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
<script type="text/javascript">
function matchpass(){
var firstpassword=[Link];
var secondpassword=[Link];
if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>
Let's validate the textfield for numeric value only. Here, we are using isNaN() function.
<script>
function validate(){
var num=[Link];
if (isNaN(num)){
[Link]("numloc").innerHTML="Enter Numeric value
only";
return false;
}else{
return true;
}
}
</script>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num">
<span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>