0% found this document useful (0 votes)
16 views

Lecture JavaScript

Uploaded by

Amisha Upadhyay
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Lecture JavaScript

Uploaded by

Amisha Upadhyay
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 91

Database Systems and Web

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>

5 1999 Asian Women's Network Training Workshop


Javascript code can be added to a web page in three ways:
1. In the page's body (runs when page loads)
2. In the page's head (used for events)
3. In a link to an external .js script file
Example
In the page's body (runs when page loads)
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
document.write("hello world");
</script>
</body>
</html>
Data Types
 JavaScript allows the same variable to contain different types of data values.
 Primitive data types
 Number: integer & floating-point numbers
 Boolean: logical values “true” or “false”
 String: a sequence of alphanumeric characters
 Composite data types (or Complex data types)
 Object: a named collection of data
 Array: a sequence of values
 Special data types
 Null: an initial value is assigned
 Undefined: the variable has been created by not yet assigned a value

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].

INE2720 – Web Application


Software Development
11 All copyrights reserved by C.C. Cheung 2003.
Array Example
<script type=“text/JavaScript”>
Car = new Array(3);
Car[0] = “Ford”;
Car[1] = “Toyota”;
Car[2] = “Honda”;
document.write(Car[0] + “<br>”);
document.write(Car[1] + “<br>”);
document.write(Car[2] + “<br>”);
</script>

 You can also declare arrays with variable length.


 arrayName = new Array();
 Length = 0, allows automatic extension of the length.
 Car[9] = “Ford”; Car[99] = “Honda”;

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

Comparison Operators Operator Description Example

== is equal to 5==8 returns false

=== is equal to (checks for both value and type) x=5

y="5"

x==y returns true

x===y returns false

!= is not equal 5!=8 returns true

> is greater than 5>8 returns false

< is less than 5<8 returns true

>= is greater than or equal to 5>=8 returns false

<= is less than or equal to 5<=8 returns true


JavaScript Operators - 4
Logical Operators Operator Description Example

&& and x=6


y=3

(x < 10 && y > 1)


returns true
|| or x=6
y=3

(x==5 || y==5)
returns false
! not x=6
y=3

!(x==y) returns true


Example -2

<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?");

if (salesTotal > 50){


if (salesTotal < 100) {
alert("The sales total is between
50 and 100.");
}
}

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>");

Note the special ++


increment operator

++ 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;

} while (count < 5);

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

for (var count = 1; count <= 5; ++count) {


if (count == 3)
break;
document.write("<p>" + count + "</p>");
}

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>

<script type = "text/javascript">



… function functionA( a , b ) {
1 …
… …
2
… …

var z = functionA( x , y ); return val;
3
… }

… 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

The average( ) function above takes three numbers as parameters, and


returns the average of the three numbers. On Line 11, when the average( )
function is called, the value 30 is returned and then stored in the variable x.
Functions – Local Variables
• Some functions declare variables within the function, called
local variables
• These variables only exist within the function and cannot be
used outside the function
Local variable
function calcShipping( state ) {
var shippingCost;
<body>
if ( state == "CT" )
shippingCost = 8.25; <script type = "text/javascript">
else if (state == "MA" ) …
shippingCost = 12.60; var state = prompt("Enter State:");
else var cost = calcShipping( state );
shippingCost = 18.20; …
</script>
return shippingCost;
} </body>

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;
}

Error: the variable shippingCost


only exists within the calcShipping( )
function
50
Example

Output
Return Statement Is Optional In Java Script

Continued on next slide


Event
JavaScript's interaction with HTML is handled through events that
occur when the user or the browser manipulates a page.

click , pressing any key, closing a window, resizing a window, etc.


onmouseover
 The onmouseover event triggers when you bring your mouse over any element
 Syntax
Example :

<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>

<p>Click the following button and see result</p>


<form>
<input type="button" onclick="sayHello()" value="Say
Hello" />
</form>
</body>
</html
Example 2
<html>
<body>
<button onclick="myFunction()">Click Me</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</body>
</html>
<HTML> <TITLE>Example of onChange Event Handler</TITLE> <HEAD> <SCRIPT LANGUAGE="JavaScript"> function valid(form){ var input=0;
input=document.myform.data.value; alert("You have changed the value from 10 to " + input ); } </SCRIPT> </HEAD> <BODY> <H3>Example of onChange Event
Handler</H3> Try changing the value from 10 to something else:<br> <form name="myform"> <input type="text" name="data" value="10" size=10
onChange="valid(this.form)"> </form> </BODY> </HTML>
The onChange event handler
❑ executes JavaScript code when input focus exits the field
after the user modifies its text.
Example :
<HTML> <TITLE>Example of onChange Event Handler</TITLE> <HEAD>
<SCRIPT LANGUAGE="JavaScript">
function valid(form){
var input=0;
input=document.myform.data.value;
alert("You have changed the value from 10 to " + input );
}
</SCRIPT>
</HEAD> <BODY>
<H3>Example of onChange Event Handler</H3>
Try changing the value from 10 to something else:<br>
<form name="myform">
<input type="text" name="data" value="10" size=10 onChange="valid(this.form)">
</form>
</BODY>
</HTML>
<HTML>
In windows <TITLE>Example
you need toof onFocus
specifyEvent
the Handler</TITLE>
event handler <HEAD></HEAD> <BODY> <H3>Example
in the <BODY> attribute. For example: of <BODY
onFocus BGCOLOR="#ffffff"
Event Handler</H3> Click your mouse in
the text box:<br> <form name="myform">
onFocus="document.bgcolor='#000000'"> <input type="text" name="data" value="" size=10 onFocus='alert("You focused the textbox!!")'> </form> </BODY>
</HTML>
onFocus: Event Handler

❑executes JavaScript code when input focus enters the field


either by tabbing in or by clicking but not selecting input from
the field.
<HTML>
<TITLE>Example of onFocus Event
Handler</TITLE>
<HEAD></HEAD>
<BODY>
<H3>Example of onFocus Event Handler</H3>
Click your mouse in the text box:<br>
<form name="myform">
<input type="text" name="data" value="" size=10
onFocus='alert("You focused the textbox!!")'>
</form>
</BODY>
</HTML>

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>

for (var y=0; y<array.length; y++)


{
e += "Element " + y + " = " + array[y] + "<br/>";
}
document.getElementById("Result").innerHTML = e;
}
</script>
<title>JS Bin</title>
</head>
Write a JavaScript program to calculate the volume of a sphere.
Write a JavaScript program to illustrate a simple calculator
HTML Forms and JavaScript
JavaScript is very good at processing user input in the web browser
HTML <form> elements receive input
Forms and form elements have unique names
Each unique element can be identified
Naming Form Elements in 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.

• JavaScript provides a way to validate form's data on the client's computer


before sending it to the web server
Form Validation
 Basic Validation :
 Make sure all the mandatory fields are filled in

Data Format Validation


 The data that is entered must be checked for correct form and value
The action attribute of <form> is used to specify the page to which data will be
given or in other words, this is the page that will process the data sent from
the <form> of the current page.

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

You might also like