Professional Documents
Culture Documents
These tags alert the browser program to begin interpreting all the
text between these tags as a script.
Hence, you must specify the precise name of the language in
which the enclosed code is written to JavaScript.
When the browser receives this signal, it employs its built-in
JavaScript interpreter to handle the code.
Cont…
<script language=”JavaScript”>
//your JavaScript code here
</script>
Here are some tips to remember when writing
JavaScript commands:
JavaScript code is case sensitive (e.g. age and Age are
different variables).
JavaScript accepts both single and double quotes.
JavaScript statements end with a semi colon (;), also
I. External File
If you want to run the same JavaScript on several pages, you can
You can use the SRC attribute of the <SCRIPT> tag to call JavaScript code from an
external text file.
Placing scripts in external files is used to separate HTML and code, make HTML and
JavaScript easier to read & maintain.
It is called by the following tag:
<SCRIPT language = "JavaScript" SRC= "filename"> </SCRIPT>
Adding JavaScript…
III. Scripts in <head> Scripts to be executed when they are called, or when an event is
triggered, are placed in functions.
Put your functions in the head section, this way they are all in one place, and they do not
JavaScript has three kind of popup boxes (Built-in global functions): Alert
box, Prompt box, and Confirm box.
alert(“message to display”);
prompt(“message to display”, “default value”);
confirm(“message to display”);
Anything between double quotes will be displayed as it is in the
web page.
However, if there is something out of quotes, it is evaluated as
expression and the result will be sent to the web page.
Cont…
The alert method produces a browser alert box. This box is often used if you want to make sure
information comes through the user.
alert() displays a modal window that presents a message to the user with a single Ok button to
dismiss the dialog box.
The prompt is often used if you want the user to input a value before entering a page.
The prompt display includes a message, field for user input, and two buttons (Ok, and Cancel).
The prompt(“”) returns string of text entered by user.
It takes two parameters:
a message providing the prompt for the response, and
a default string which is used to fill in the text field.
Example (alert and prompt)
Cont…
A confirm dialog box presents a message in a modal dialog box along
with Ok and Cancel buttons which is often used if you want the user to
verify or accept something.
Such dialog boxes can be used to ask the user a question. For example:
you want to take the user’s confirmation before saving, updating or deleting
data.
The dialog box returns a Boolean value of Ok=true, and Cancel=false;
Comments in JavaScript
Comments are used to add description to specific code section so as to
describe what the code performs.
JavaScript supports two types of comments:
Comments on a single line are preceded by / / .
Comments that span multiple lines are preceded by / * and
followed by * /
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<script type="text/javascript">
var a=10
var b=23.5
Result=a+b
document.write(Result)
</script>
</body>
</html>
Data types in JavaScript
1. Numeric (integer, double, float)
2. Boolean (true or false): often used in conditional testing
3. String
4. Array, Object, null, Undefined
Data Type Conversions…
Operator Description
- Perform Subtraction
* Multiply numbers
/ Divide numbers
++ Increment
-- Decrement
Operators and Expressions…
Example:
<script language=“JavaScript”>
var x;
var y=5;
x = y+2; //x=7
x = y-2; //x=3
x = y*2; //x=10
x = y/2; //x=2.5
x = y%2; //x=1
x = ++y; //x=6
x = --y; //x=4
</script>
Operators and Expressions…
Operator Description
= Assignment operator
+= Add and then assign
<script language=“JavaScript”>
var x=5;
var y=5;
x=y; //x=5;
x+=y; //x=10
x-=y; //x=5
x*=y; //x=25
x/=y; //x=5
</script>
Operators and Expressions…
Symbol Description
== Equal to
!= Not equal to
=== Strictly (Exactly) equal to (value and type)
!== Strictly not equal to (not equal value or not equal type)
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
Example
Output:
true
true
false
true
false
Operators and Expressions…
Operator Description
&& And
|| Or
! Not
Given that x=6 and y=3, the table shows logical operators:
Example Result
(x<10 && y>1) true
(x==5 || y==5) false
!(x==y) true
5. Working with Conditional
Statements
Conditional statements are used to perform different
actions based on conditions.
Example:
Cont…
If . . . else condition
syntax:
if (expression)
{ statement ;}
else
{ statement2;}
Cont…
if else-if condition..
if (condition) {
statement1
}
else if(condition){
statement2
}
else {
statement3
}
We use if else-if when we have more than two conditions to
check.
Example
Cont…
Switch Statement
A switch statement allows a program to evaluate an expression and attempt to match the
expression's value to a case label.
The value of the expression is compared with the value of each case, if a match is
found, the program executes the associated statement.
switch (expression) {
case 1:
statements1
break;
case 2:
statements2
break;
...default:
statements default
}
Looping Statements in JavaScript
<html>
<head>
<title> Java Script</title>
</head>
<body>
<script language="JavaScript">
for(var i=0; i<=5; i++)
{
document.write("The value of i is="+i+"<br>");
}
</script>
</body>
</html> Output
The value of i is=0
The value of i is=1
The value of i is=2
The value of i is=3
The value of i is=4
The value of i is=5
Working with Loops…
2. do...while Statement
The do...while statement repeats until a specified condition
evaluates to false.
A do...while statement looks as follows:
do
{
statement //code to be executed
}
while (condition);
Statement executes once before the condition is checked. If
condition is true, the statement executes again. At the end of every
execution, the condition is checked. When the condition is false,
execution stops.
Working with Loops…
Example:
var i=5;
do
{
document.write("tick "+i+"<br>");
i--;
}
while(i>0);
3. while Statement
A while statement executes its statements as long as a specified
condition evaluates to true.
A while statement looks as follows:
while (condition)
{
statement
}
Array in JavaScript
• An array is a special variable, which can store multiple values
in one single variable.
• Arrays are objects.
• Array indexes are zero based which means the first item is zero
(0).i.e. it holds paired index and value.
Why Arrays?
There are several advantages to using JavaScript arrays:
• They are efficient for storing and retrieving data.
• They can be easily manipulated due it has different
methods.
• They have a rich set of methods for working with data.
Cont…
Declaring arrays:
1. Literal method:
-Using square bracket [ ]
2. Constructor method:
-Using array keyword: new Array ( )
braces { }.
Cont…
called.
The return Statement
The return statement is used to specify the value that is
return statement.
Reading Assignment
Math.
These include trigonometric, logarithmic, exponential, and other
functions.
For example: if you want to use the trigonometric function sine,
you would write:
Math.sin(1.56)
Note that all trigonometric methods of Math take arguments in
radians.
Cont…
Math.PI 3.141592653589793116 π
Data objects are static, i.e. you should have refresh it to get
correct date.
var dateObjectName = new Date([parameters])
The parameter can be:
new Date(“Month dd, yyyy hh:mm:ss”)
new Date(“Month dd, yyyy”)
new Date(yy,mm,dd,hh,mm,ss)
new Date(yy,mm,dd)
new
Date(milliseconds)
Cont…
Method Value Range Description
dateObj.getTime() 0-... returns Milliseconds since 1/1/70 00:00:00 GMT
dateObj.getYear() 70-... returns Specified year minus 1900
returns four-digit year for 2000+
dateObj.getFullYear() 1970-... returns four-digit year (Y2K-compliant)
dateObj.getMonth() 0-11 returns Month within the year (January = 0)
dateObj.getDate() 1-31 returns Date within the month
dateObj.getDay() 0-6 returns Day of week (Sunday = 0)
dateObj.getHours() 0-23 returns Hour of the day in 24-hour time
dateObj.getMinutes() 0-59 returns Minute of the specified hour
dateObj.getSeconds() 0-59 returns Second within the specified minute
dateObj.setTime(val) 0-... sets Milliseconds since 1/1/70 00:00:00 GMT
dateObj.setYear(val) 70-... sets Specified year minus 1900
sets four-digit year for 2000+
dateObj.setMonth(val) 0-11 sets Month within the year (January = 0)
dateObj.setDate(val) 1-31 sets Date within the month
dateObj.setDay(val) 0-6 sets Day of week (Sunday = 0)
dateObj.setHours(val) 0-23 sets Hour of the day in 24-hour time
dateObj.setMinutes(val) 0-59 sets Minute of the specified hour
dateObj.setSeconds(val) 0-59 sets Second within the specified minute
Example:
Output
Sun Nov 12 2023 20:47:21 GMT-0800 (Pacific
Standard Time)
10
2023
Cont…
2.3 String Object
A string is any text inside a quote pair.
2. You can also create a string object using the more formal syntax that
involves the new keyword and a constructor function like:
var stringVar = new String(“Hello there”);
Cont…
Method Description
charAt(index) Returns the character at the specified index.
charCodeAt(index) Returns a number indicating the Unicode value of the character at the given index.
concat(string) Combines the text of two strings and returns a new string.
indexOf(string, [start]) Returns the index within the calling String object of the first occurrence of the
specified value, or -1 if not found.
lastIndexOf(string,[start]) Returns the index within the calling String object of the last occurrence of the
specified value, or -1 if not found.
localeCompare(string2) Returns a number indicating whether a reference string comes before or after or is
the same as the given string in sort order.
length Returns the length of the string.
match(regExpression) Used to match a regular expression against a string.
replace(regExpression,replacer) Used to find a match between a regular expression and a string, and to replace the
matched substring with a new substring.
search(regExpression) Executes the search for a match between a regular expression and a specified string.
slice(startIndex [,end]) Extracts a section of a string and returns a new string.
split(delimiter [,limit]) Splits a String object into an array of strings by separating the string into substrings.
substr(start [, length]) Returns the characters in a string beginning at the specified location through the
specified number of characters.
substring(start, end) Returns the characters in a string between the two indexes into a string.
toLowerCase() Returns the calling string value converted to lower case.
toUpperCase() Returns the calling string value converted to uppercase.
toString() Returns a string representing the specified object.
Cont…
Example:
Data Validation in JavaScript
• Data validation is the process of ensuring that the user input is
correct, and useful.
• Typical validation tasks are:
• has the user filled in all required field?
• has a user entered a valid date?
• has the user entered text in numeric field?
• Most often, the purpose data validation is to ensure correct user input.
If an input field contains invalid data, it display a message.
• 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 Form Validation
• It is important to validate the
form submitted by the user
because it can have
inappropriate values. So,
validation is must to
authenticate user.
• HTML form validation can be
done by JavaScript.
• If a form field (Fname) is empty,
this function alerts a message,
and returns false, to prevent the
form from being submitted.
• Through JavaScript, we can
validate name, password,
email, date, mobile numbers
and more fields.
JavaScript DOM (Document object Model)
onSelect
A select event occurs when a user selects some of the text within a text or
textarea field.
Cont…
onError
An error event occurs when the loading of a document or image causes an error
onFocus
A focus event occurs when a field receives input focus by tabbing with the
keyboard or clicking with the mouse.
onKeyDown, onKeyPress, onKeyUp
A keyDown, keyPress, or keyUp event occurs when a user depresses a key,
presses or holds down a key, or releases a key, respectively
onSubmit
Thank you!!
Any Query?