Lecture JavaScript
Lecture JavaScript
JAVA Script
Lecture 5
JAVA Script
What is JavaScript?
Browsers have limited functionality
Text, images, tables, etc.
JavaScript allows for interactivity
Perform calculations
Validation of input
Browser/page manipulation
Reacting to user actions
A type of programming language (Object Based and Interpreted)
Easy to learn
Developed by Netscape
Now works in all major browsers
is used in millions of Web pages to improve the design, validate forms, detect browsers,
create cookies, and much more
How Does It Work?
Embedded within HTML page
View source
Executes on client
Fast, no connection needed once loaded
Simple programming statements combined with HTML tags
Interpreted (not compiled)
No special tools required
Ending Statements With a Semicolon?
Semicolons are optional! Required if you want to put more than one statement on a
single line.
Basic HTML Document Format
<HTML>
<HTML> See what it
<HEAD>
<HEAD> looks like:
<TITLE>WENT'99</TITLE>
<TITLE>WENT'99</TITLE>
</HEAD>
</HEAD>
<BODY>
<BODY>
Went'99
Went'99
</BODY>
</BODY>
</HTML>
</HTML>
8
Numeric Data Types
It is an important part of any programming language for doing arithmetic
calculations.
JavaScript supports:
Integers: A positive or negative number with no decimal places.
Ranged from –253 to 253
Floating-point numbers: usually written in exponential notation.
3.1415…, 2.0e11
9
var length = 16; // Number
var lastName = "Johnson"; // String
var cars = ["Saab", "Volvo", "BMW"]; // Array
var x = {firstName:"John", lastName:"Doe"}; // Object
Javascript has dynamic types
var x; // Now x is undefined
var x = 5; // Now x is a Number
var x = "John"; // Now x is a String
You can use the JavaScript typeof operator to find the type of a JavaScript
variable:
typeof "John" // Returns string
typeof 3.14 // Returns number
typeof false // Returns boolean
typeof [1,2,3,4] // Returns object
typeof {name:'John', age:34} // Returns object
Array
An Array contains a set of data represented by a single variable name.
Arrays in JavaScript are represented by the Array Object, we need to “new
Array()” to construct this object.
The first element of the array is “Array[0]” until the last one Array[i-1].
E.g. myArray = new Array(5)
We have myArray[0,1,2,3,4].
12
JavaScript Operators
Operator Description Example Result
Arithmetic Operators + Addition x=2 4
y=2
x+y
- Subtraction x=5 3
y=2
x-y
* Multiplication x=5 20
y=4
x*y
/ Division 15/5 3
5/2 2.5
% Modulus (division remainder) 5%2 1
10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--
JavaScript Operators – 2
Operator Example Is The Same As
Assignment Operators
= 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
JavaScript Operators - 3
y="5"
(x==5 || y==5)
returns false
! not x=6
y=3
<script>
s1=12
s2=28
total=s1+s2
document.write(“Total is: “,total)
</script>
JavaScript Popup Boxes
Alert Box
An alert box is often used if you want to make sure information comes
through to the user.
When an alert box pops up, the user will have to click "OK" to proceed.
<script>
alert("Hello World!")
</script>
JS Examples -1
Y=20x+12 and x=3
<script>
x=3
y=20*x+12
alert(y)
</script>
JavaScript Popup Boxes - 2
Confirm Box
A confirm box is often used if you want the user to verify or accept
something.
When a confirm box pops up, the user will have to click either "OK" or
"Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the
box returns false.
<script>
confirm("Get a message?");
</script>
JavaScript Popup Boxes – 2 (Cont..)
var r = confirm("Press a button");
if (r == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
JavaScript Popup Boxes – 2 (Cont..)
if (confirm("Do you agree")) {
alert("You agree")
}
else{
alert ("You do not agree")
};
JavaScript Popup Boxes - 3
Prompt Box
A prompt box is often used if you want the user to input a value before
entering a page.
When a prompt box pops up, the user will have to click either "OK" or
"Cancel" to proceed after entering an input value.
If the user clicks "OK“, the box returns the input value. If the user clicks
"Cancel“, the box returns null.
<script>
prompt("What is your favorite color?", "");
</script>
Conditional and Repetition Statements
Conditional statements:
if statement - use this statement if you want to execute some code only if a specified condition
is true
if...else statement - use this statement if you want to execute some code if the condition is true
and another code if the condition is false
if...else if....else statement - use this statement if you want to select one of many blocks of code
to be executed
switch statement - use this statement if you want to select one of many blocks of code to be
executed
Repetition structure: four in JavaScript
while
do…while
for
for…in
if...else Statements
• Executes one action if the condition is true
and a different action if the condition is false
• Syntax for an if . . . else statement
if (conditional expression)
statement;
else
statement;
25
if...else Statements (cont)
• Example:
var today = "Tuesday"
if (today == "Monday")
console.log("Today is Monday");
else
console.log("Today is not Monday");
26
Nested if and if...else Statements
(cont)
• Example:
var salesTotal = prompt("What is the sales
total?");
27
Switch- Case
switch Statements (cont)
• Example:
var age = prompt("Please enter age: ");
switch ( age ) {
case 25:
alert("25 is a good age");
alert("lots of fun");
case "thirty":
alert("Thirty is a good age");
case 40:
alert("40 is a great age");
default:
alert("that is a good age");
}
29
While Loop and Do …While
Syntax
Syntax
while Statements (cont)
var x = 1;
while ( x <= 5) {
console.log( x );
++x;
}
console.log("<p>You have printed 5
numbers.</p>");
++ increment operator
adds 1 to the variable
31
Output
Example
do...while Statements (cont)
• Example:
var count = 0;
do {
console.log("The count is: " + count );
++count;
33
For Loop
for Statements (cont’d.)
• Example:
var daysOfWeek = new Array();
daysOfWeek[0] = "Monday";
daysOfWeek[1] = "Tuesday";
daysOfWeek[2] = "Wednesday";
daysOfWeek[3] = "Thursday";
daysOfWeek[4] = "Friday";
daysOfWeek[5] = "Saturday";
daysOfWeek[6] = "Sunday";
for (var count = 0; count < daysOfWeek.length; +
+count) {
console.log(daysOfWeek[count] );
}
35
Example
Using Break Statements Execution
37
Break Statement
Output
Using CONTINUE Statements to Restart
Execution (cont’d.)
for (var count = 1; count <= 5; ++count) {
if (count == 3)
continue;
console.log(count );
}
39
Continue Statement Output
Functions
A function is a group of reusable code which can be called
anywhere in your program. This eliminates the need of writing the same
code again and again. It helps programmers in writing modular codes.
Function Syntax
Placement of user-defined functions
• User defined functions should be declared in a SCRIPT
element in the HEAD section of the web page
<html> <body>
<head>
<script type = "text/javascript"> …
function sum( a , b ) { <script type = "text/javascript">
return a + b; var x = sum( 15 , 12 );
} var t = avg( 105 , 65 );
function avg( a , b ) { </script>
return ( a + b ) / 2; …
}
</script> </body>
</head> </html>
…
call functions
define functions
43
Placement of user-defined functions (2)
• Many times user-defined functions will be defined in an
external JavaScript file
function sum( a , b ) { functions.js
return a + b; <body> page.html
}
function avg( a , b ) { …
return ( a + b ) / 2; <script type = "text/javascript">
} var x = 10;
var y = 25;
<html> page.html var z = sum( x , y );
<head> </script>
<script type = "text/javascript" …
src = "functions.js" >
</script> </body>
</head> </html>
…
44
Functions – Control Flow
• When a function is called, the control flow jumps to the
function code
<body>
… 4
… 5
…
…
</script>
</body>
45
A function named helloAlert( ) in the HEAD section of the
webpage.
A function named welcome( ) that takes in one parameter, named user.
When the function is called, the argument "John Smith" is passed to
the function.
This function will display the message box "Welcome John Smith to
my website!" when the function is called in the webpage.
Functions With a Return Value
49
Functions – Local Variables (cont)
• If we tried to access a local variable outside the function, we
would get an error
<body>
function calcShipping( state ) {
var shippingCost; <script type = "text/javascript">
…
if ( state == "CT" ) var state = prompt("Enter State:");
shippingCost = 8.25; var cost = calcShipping( state );
else if (state == "MA" ) …
shippingCost = 12.60; document.write( shippingCost );
else </script>
shippingCost = 18.20;
</body>
return shippingCost;
}
Output
Return Statement Is Optional In Java Script
<html> <html>
<element onmouseover="function_name()"> <head>
</html> <script>
// this function will execute when onmouseover is triggered
<script> function func()
// defining the function function_name {
function function_name() // an alert will pop-up when onmouseover gets triggered
{ alert("onmouseover alert.");
// function script }
} </script>
</script> </head>
<body>
<!-- creating an onmouseover event for a <b> tag-->
<b onmouseover = "func()">
Bring the cursor here to get an alert.
</b>
</body>
</html>
<html>
<head>
<script>
// this function will execute when onmouseover is triggered
function func()
{
// an alert will pop-up when onmouseover gets triggered
alert("onmouseover alert.");
}
</script>
</head>
<body>
<!-- creating an onmouseover event for a <b> tag-->
<b onmouseover = "func()">
Bring the cursor here to get an alert.
</b>
</body>
</html>
After the mouseoverevent
Other Events
JavaScript Events
• Examples of HTML events:
– When a user clicks the mouse
– When a web page has loaded
– When an image has been loaded
– When the mouse moves over an element
– When an input field is changed
– When an HTML form is submitted
– When a user strokes a key
60
onclick/onmouseover Events
• The onclick event is triggered when the user clicks
the mouse on a specified HTML element
• The onmouseover event is triggered when the user
mouses over a specified HTML element.
<html>
<body>
<h1>Test Events Page</h1>
<h2 onclick="alert('you clicked me')" > Click on me!</h2>
<h2 onmouseover="alert('you hovered over me')" >
Hover over me!</h2>
</body>
</html>
61
onClick
<html>
Event Handler Example
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
FaaDoOEngineers.com
onSubmit:
An onSubmit event handler calls JavaScript code when the form is
submitted.
<HTML>
<TITLE> Example of onSubmit Event Handler </TITLE>
<HEAD>
</HEAD>
<BODY>
<H3>Example of onSubmit Event Handler </H3>
Type your name and press the button<br>
<form name="myform" onSubmit="alert('Thank you ' + myform.data.value
+'!')">
<input type="text" name="data">
<input type="submit" name ="submit" value="Submit this form">
</form>
</BODY>
onSelect:
A onSelect event handler executes JavaScript code when the user
selects some of the text within a text or textarea field.
<HTML>
<TITLE>Example of onSelect Event Handler</TITLE>
<HEAD></HEAD>
<BODY>
<H3>Example of onSelect Event Handler</H3>
Select the text from the text box:<br>
<form name="myform">
<input type="text" name="data" value="Select This" size=20
onSelect="alert('This is an example of onSelect!!')">
</form>
</BODY>
</HTML>
FaaDoOEngineers.com
Write a JavaScript program to add items in an blank array
and display the items.
Solution
<!DOCTYPE html>
<html>
<head>
<script> <body>
var x = 0;
var array = Array();
<input type="text" id="text1"></input>
<input type="button" id="button1"
function add_element_to_array() value="Add"
{
array[x] = document.getElementById("text1").value;
onclick="add_element_to_array();"></input>
alert("Element: " + array[x] + " Added at index " + x); <input type="button" id="button2"
x++; value="Display"
document.getElementById("text1").value = "";
}
onclick="display_array();"></input>
<div id="Result"></div>
function display_array() </body>
{
var e = "<hr/>";
</html>
<form name="addressform">
Name: <input name="yourname"><br />
Phone: <input name="phone"><br />
Email: <input name="email"><br />
</form>
Forms and JavaScript
document.formname.elementname.value
Thus:
document.addressform.yourname.value
document.addressform.phone.value
document.addressform.email.value
Using Form Data
Personalising an alert box
<form name="alertform">
Enter your name:
<input type="text" name="yourname">
<input type="button" value= "Go"
onClick="window.alert('Hello ' +
document.alertform.yourname.value);">
</form>
Form validation
Form Validation
• Form validation normally used to occur at the server.
• 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.
https://o7planning.org/12273/javascript-form-validation
Process_action.html
Data field validation
Access a field data through the field ID.
https://o7planning.org/12273/javascript-form-validation
Access Form fields through the name attribute:
Example: Ask an user to enter a number between 0 and 10.
Validate automatically
The browser can automatically validate several types of data on the form, such as
addinga required attribute to a form field to tell the browser that this field is mandatory. The browser
will automatically check and notify an user if an user does not enter that field.
https://o7planning.org/12273/javascript-form-validation
References for form validation
https://o7planning.org/12273/javascript-form-validation