JavaScript and HTML forms

coordinatedcapableΛογισμικό & κατασκευή λογ/κού

4 Νοε 2013 (πριν από 3 χρόνια και 9 μήνες)

91 εμφανίσεις

JavaScript and HTML forms

Week 9

Information Technologies 17:610:550:01

-

Fall 2008
-




Part of slides are adapted from David Reed.

Announcements


Assignment 3 is due on Friday at 5pm


MS Access 2007 CDs available


Assignment 2 grades available this week


I will send an email when they are done and ready for pick up


Available in Room 214 . Ask for folder for class 17:610:550:01 (section 1)

Mon

Friday 9:00
-
5pm


Or next class


Assignment 3 grades available next week as well!


Next week we will review all assignments and important concepts of
lecture in a Review for Exam



Agenda


JavaScript and Client
-
side Programming


JavaScript elements


Event Handling and HTML forms




Review MS Access (creating tables, relationships, queries)


Lab session


Either work on Assignment 3 or practice JavaScript

EXAMPLE


Example of JavaScript use

Client
-
Side Programming


HTML is good for developing
static

pages


can specify text/image layout, presentation, links, …


Web page looks the same each time it is accessed



in order to develop interactive/reactive pages, must integrate programming in some form or
another


client
-
side programming


programs are written in a separate programming (or scripting) language

e.g., JavaScript, JScript, VBScript


programs are embedded in the HTML of a Web page, with tags to identify the program
component

e.g.,

<script type="text/javascript"> … </script>


the browser executes the program as it loads the page, integrating the dynamic output of
the program with the static content of HTML


could allow the user to input information and process it, might be used to validate input
before it’s submitted to a remote server

Client
-
Side Programming


HTML is good for developing
static

pages


can specify text/image layout, presentation, links, …


Web page looks the same each time it is accessed



in order to develop interactive/reactive pages, must integrate programming in some form or
another


client
-
side programming


programs are written in a separate programming (or scripting) language

e.g., JavaScript, JScript, VBScript


programs are embedded in the HTML of a Web page, with tags to identify the program
component

e.g.,

<script type="text/javascript"> … </script>


the browser executes the program as it loads the page, integrating the dynamic output of
the program with the static content of HTML


could allow the user to input information and process it, might be used to validate input
before it’s submitted to a remote server

Scripts


a scripting language is a simple,
interpreted

programming language


scripts are embedded as plain text, interpreted by application


JavaScript:



-

the first Web scripting language, developed by
Netscape in 1995

-

Object oriented programming language





Common Scripting Tasks


adding dynamic features to Web pages


validation of form data


image rollovers


time
-
sensitive or random page elements



defining programs with Web interfaces


utilize buttons, text boxes, clickable images, prompts, etc


limitations of client
-
side scripting


since script code is embedded in the page, it is viewable to the world


for security reasons, scripts are limited in what they can do

e.g., can't access the client's hard drive


since they are designed to run on any machine platform, scripts do not contain platform
specific commands


script languages are not full
-
featured

e.g., JavaScript objects are very crude, not good for large project development

JavaScript


JavaScript code can be embedded in a Web page using
SCRIPT

tags


the output of JavaScript code is displayed as if directly entered in HTML

<html>

<!

-

COMP519 js01.html 16.08.06
--
>


<head>


<title>JavaScript Page</title>

</head>


<body>


<script type="text/javascript">


// silly code to demonstrate output



document.write("
Hello world
!");



document.write("<p>How are <br/>" +


"<i>you</i>?</p>");


</script>



<p>Here is some static text as well.


</p>

</body>

</html>

document.write

displays text in the page


text to be displayed can include HTML
tags


the tags are interpreted by the browser
when the text is displayed



as in C++/Java, statements end with

;

but a line break is
also

interpreted as the end
of a statement


JavaScript comments similar to C++/Java


//

starts a single line comment


/*…*/

enclose multi
-
line comments

view page

JavaScript Objects Examples


Window


The top level object in the JavaScript hierarchy. The Window object represents a browser
window. A Window object is created automatically with every instance of a <body> or
<frameset> tag


Document


Represents the entire HTML document and can be used to access all elements in a page


Array


Data …



Every object has associated with it:


Properties
-

values associated with an object


Methods
-

actions that can be performed on objects.

document Object

Both IE and Netscape allow you to access information about an HTML document
using the
document

object
(Note: not a class!)

<html>

<!

-

COMP519 js13.html 16.08.2006
--
>


<head>


<title>Documentation page</title>

</head>


<body>


<table width="100%">


<tr>


<td><small><i>


<script type="text/javascript">


document.write(document.URL)
;


</script>


</i></small></td>


<td style=“text
-
align: right;"><small><i>


<script type="text/javascript">


document.write(document.lastModified)
;


</script>


</i></small></td>


</tr>


</table>

</body>

</html>

document.write(…)

method that displays text in
the page



document.URL

property that gives the
location of the HTML
document



document.lastModified

property that gives the date &
time the HTML document was
last changed

view page

Agenda


JavaScript and Client
-
side Programming


JavaScript elements


Event Handling and HTML forms

JavaScript Elements


data types & variables


Operators


Statements


Functions


Control structures


Arrays Object


Date Object


Data Type and Variables


Data types


Boolean:

true, false


Number:

5, 9,

3.1415926


String:


“Hello World”


A “variable” holds a value of a specific data type


Represented as symbols:
x, celsius


In JavaScript,
var

“declares” a variable

var b = true;

create a boolean
b

and set it to true

var n = 1;

create a number
n

and set it to 1

var s = “hello”;

create a string
s

and set it to “hello”

JavaScript Data Types & Variables


JavaScript has only three primitive data types

String
:
"foo" 'howdy do' "I said 'hi'." ""

Number
:
12 3.14159 1.5E6

Boolean
:
true false

<html>

<!

-

COMP519 js02.html 16.08.06
--
>


<head>


<title>Data Types and Variables</title>

</head>


<body>


<script type="text/javascript">


var x=1024, y;




y=x;

x = "foobar";


document.write("<p>x = " + y + "</p>");


document.write("<p>x = " + x + "</p>");


</script>

</body>

</html>


variable names are sequences of letters,
digits, and underscores that
start with a
letter or an underscore


variables names are
case
-
sensitive


you don't have to declare variables, will be
created the first time used, but it’s better if
you use
var

statements



var

pi=1024, y;


variables are loosely typed, can be
assigned different types of values

view page

Operators


-
x




reverse the sign of x (negation)


6+5




Add 6 and 5 (numeric)


“Hello” + “World”


Concatenate two strings


2.1 * 3



Multiply two values


x++




increase value of x by 1



x = 5



set the value of x to be 5


x += y



x = x + y


x *= 5



x = x * 5

Statements


In JavaScript, instructions end with a semicolon


If missing at end of line, it is automatically inserted



Simple assignment statements

celsius = 5/9 * (f
-
32);



Statements that invoke a method (function)

Temperature.toCelsius(104);



Return a value from a method (function)

return celsius;

Functions


Reusable code for complex “statements”


Takes one or more values as “parameters”


Returns at most one value as the “result”


function convertToCelsius(f) {


var celsius = 5/9 * (f
-
32);


return celsius;

}


c = convertToCelsius(60);

function convertToCelsius(f) {


var celsius = 5/9 * (f
-
32);


return celsius;

}

var f = 60;

c = convertToCelsius(f);

Function
declaration

Function call

<html>

<!

-

COMP519 js06.html 16.08.2006
--
>


<head>


<title>Prime Tester</title>



<script type="text/javascript">



function isPrime(n)


// Assumes: n > 0


// Returns: true if n is prime


{


// CODE OMITTED FOR SIMPLICTY




}


</script>

</head>


<body>


<script type="text/javascript">


testNum = parseFloat(prompt("Enter a positive integer", "7"));




if (
isPrime(testNum)
) {


document.write(testNum + " <b>is</b> a prime number.");


}


else {


document.write(testNum + " <b>is not</b> a prime number.");


}


</script>

</body>

</html>

Function definitions
(usually) go in the
<head>
section



<head>

section is
loaded first, so then
the function is
defined before code
in the
<body>

is
executed

view page

Algorithms


A sequence of well
-
defined instructions designed to accomplish a certain task



Derived from the name of the Persian mathematician Al
-
Khwarizmi

Basic Control Structures


Sequential


Perform instructions one after another



Conditional


Perform instructions contingent on something



Repetition


Repeat instructions until a condition is met

Not much different from cooking recipes!

Sequential Control Structure





a = 2


b = 3


c = a * b

Conditional Selection Control Structure


if (gender == “male”) {


greeting = “Hello, Sir”

}

else {


greeting = “Hello,
Madam”

}

Generating Boolean Results


x == y


true if x and y are equal


x != y


true if x and y are not equal


x > y


true if x is greater than y


x <= y


true if x is smaller than or equal to y


x && y


true if both x and y are true


x || y


true if either x or y is true


!x



true if x is false

Repetition Control Structure



Program Example 1:


n = 1

while ( n <= 10) {


document.writeln(n)


n++

}


Program 2:


For (n = 1; n <= 10; n++) {


document.writeln(n)

}


Arrays


arrays store a sequence of items, accessible via an index

since JavaScript is loosely typed, elements do not have to be the same type



to create an array, allocate space using
new
(or can assign directly)


items = new Array(10);


// allocates space for 10 items


items = new Array();


// if no size given, will adjust
dynamically


items = [0,0,0,0,0,0,0,0,0,0]; // can assign size & values []



to access an array element, use
[]


for (i = 0; i < 10; i++) {


items[i] = 0;


// stores 0 at each index


}






the
length

property stores the number of items in the array


for (i = 0; i < items.length; i++) {


document.write(items[i] + "<br>"); // displays elements

}

Date Object


String & Array are the most commonly used classes in JavaScript


other, special purpose classes & objects also exist



the Date class can be used to access the date and time



to create a Date object, use new & supply year/month/day/… as desired


today = new Date(); // sets to current date & time


newYear = new Date(2002,0,1); //sets to Jan 1, 2002 12:00AM



methods include:


newYear.getYear()



can access individual components of a date

newYear.getMonth()



newYear.getDay()



newYear.getHours()



newYear.getMinutes()



newYear.getSeconds()



newYear.getMilliseconds()


Date Example

<html>

<!

-

COMP519 js11.html 16.08.2006
--
>


<head>


<title>Time page</title>

</head>


<body>


Time when page was loaded:


<script type="text/javascript">


now = new Date();



document.write("<p>" + now + "</p>");



time = "AM";


hours = now.getHours();


if (hours > 12) {


hours
-
= 12;


time = "PM"


}


else if (hours == 0) {


hours = 12;


}


document.write("<p>" + hours + ":" +


now.getMinutes() + ":" +


now.getSeconds() + " " +


time + "</p>");


</script>

</body>

</html>

by default, a date will be displayed in
full, e.g.,


Sun Feb 03 22:55:20
GMT
-
0600 (Central
Standard Time) 2002




can pull out portions of the date using
the methods and display as desired


here, determine if "AM" or "PM" and
adjust so hour between 1
-
12


10:55:20 PM


view page

Agenda


JavaScript and Client
-
side Programming


JavaScript elements


Event Handling and HTML forms

Interactive Pages Using Prompt

<html>

<!
--

COMP519 js05.html 16.08.2006
--
>


<head>


<title>Interactive page</title>

</head>


<body>


<script type="text/javascript">


userName =
prompt("What is your name?", "");



userAge = prompt("Your age?", "");


userAge = parseFloat(userAge);



document.write("Hello " + userName + ".")


if (userAge < 18) {


document.write(" Do your parents know " +


"you are online?");


}


else {


document.write(" Welcome friend!");


}

</script>



<p>The rest of the page...</p>

</body>

</html>


prompt is a method of the
Window object


1
st

argument: the prompt
message that appears in the
dialog box


2
nd

argument: a default value
that will appear in the box (in
case the user enters nothing)


the function returns the value
entered by the user in the
dialog box (a string)


if value is a number, must use
parseFloat to convert


forms will provide a better
interface for interaction




view page

Event
-
driven programs


computation within a Web page is rarely serial instead, the page
reacts

to events such as mouse clicks, buttons, …



much of JavaScript's utility is in specifying actions that are to
occur in the page as a result of some event


the programmer may have little or no control over when code
will (if ever) be executed, e.g., code that reacts to a button
click


there is no set sequence, the page waits for events and reacts

OnLoad & OnUnload


the simplest events are when
the page is loaded or unloaded



the
onload

attribute of the
<body>

tag specifies JavaScript
code that is automatically
executed when the page is
loaded



the

onunload

attribute similarly
specifies JavaScript code that is
automatically executed when the
browser leaves the page



alert

is a method of the Window
objects which opens a dialogue
box and takes the focus away
from the current window and
forces the web browser to read
the message.

<html>


<!

-

COMP519 form01.html 12.10.2006
--
>



<head>


<title>Hello/Goodbye page</title>



<script type="text/javascript">


function Hello()


{


globalName=prompt("Welcome to my page. " +


"What is your name?","");


}



function Goodbye()


{


alert("So long, " + globalName +


" come back real soon.");


}


</script>


</head>



<body
onload="Hello();"

onunload="Goodbye();"
>


Whatever text appears in the page.


</body>

</html>

view page

HTML forms


most event
-
handling in JavaScript is associated with form elements


an HTML form is a collection of elements for handling input, output,
and events in a page


<form name="
FormName
">



</form>




form elements might include:

for input:

button
, selection list, radio button,
check box
, password,


for input/output:

text box
, text area, …



Button Element

<html>


<!

-

COMP519 form02.html 12.10.2006
--
>


<head>


<title> Fun with Buttons</title>



<script type="text/javascript"


src="http://www.csc.liv.ac.uk/~martin/teaching/comp519/JS/random.js">


</script>


</head>



<body>


<form name="ButtonForm">


<input type="
button
" value="
Click for Lucky Number
"


onclick=“var
num = RandomInt(1, 100);


alert('The lucky number for the day is ' +
num);
" />


</form>


</body>

</html>


the simplest form element is a button


analogous to a real
-
world button, a click can be used to trigger events



<input type="
button
" value="
LABEL
" onclick="
JAVASCRIPT_CODE
"/>


view page

Buttons & Functions

<html>


<!

-

COMP519 form03.html 13.10.2006
--
>


<head>


<title>Fun with Buttons</title>



<script type="text/javascript">


function Greeting()


// Results: displays a time
-
sensitive greeting


{


var now = new Date();


if (now.getHours() < 12) {


alert("Good morning");


}


else if (now.getHours() < 18) {


alert("Good afternoon");


}


else {


alert("Good evening");


}


}


</script>


</head>



<body>


<form name="ButtonForm">


<input type="
button
" value="
Click for Greeting
"


onclick="
Greeting();
" />


</form>


</body>

</html>

for complex tasks
,

should define function(s)
and have the
onclick

event trigger a function
call


alert


will open a
dialogue
box that pops up and
takes the focus away
from the current
window and forces the
web browser to read
the message.


view page

Buttons & Windows


alert boxes are fine for displaying short, infrequent messages


not well
-
suited for displaying longer, formatted text


not integrated into the page, requires the user to explicitly close the box





QUESTION: could we instead use document.write ?

NO
--

would overwrite the current page, including form elements


but could open a new browser window and write there



var OutputWindow = window.open();



// open a window and assign








// a name to that object








// (first arg is an HREF)


OutputWindow.document.open();



// open that window for








// writing


OutputWindow.document.write("
WHATEVER
");

// write text to that








// window as before


OutputWindow.document.close();

// close the document in that window

Window Example

<html>


<!
-


COMP519 form04.html 13.10.2006
--
>




<head>


<title> Fun with Buttons </title>


<script type="text/javascript">


function Help()


// Results: displays a help message in a separate window


{


var OutputWindow = window.open();


OutputWindow.document.open();



OutputWindow.document.write("
This might be a context
-
" +


"
sensitive help message, depending on the

" +


"
application and state of the page.
");



OutputWindow.document.close();


}


</script>


</head>



<body>


<form name="ButtonForm">


<input type="button" value="Click for Help"


onclick="Help();" />


</form>


</body>

</html>

view page

Window Example Refined

<html>


<!
-


COMP519 form05.html 13.10.2006
--
>


<head>


<title> Fun with Buttons </title>


<script type="text/javascript">


function Help()


// Results: displays a help message in a separate window


{


var OutputWindow =


window.open("", "",


"
status=0
,
menubar=0
,
height=200
,
width=200
");


OutputWindow.document.open();



OutputWindow.document.write("This might be a context
-
" +


"sensitive help message, depending on the " +


"application and state of the page.");



OutputWindow.document.close();


}


</script>


</head>


<body>


<form name="ButtonForm">


<input type="button" value="Click for Help"


onclick="Help();" />


</form>


</body>

</html>

can have
arguments to

window.open


1
st

arg specifies
HREF

2
nd

arg specifies
internal name

3
rd

arg specifies
window
properties (e.g.,
size)

view page

Text Boxes


a text box allows for user input


unlike prompt, user input persists on the page & can be edited


<input type="text" id=“BOX_NAME” name="BOX_NAME"… />


optional attributes:

size

: width of the box (number of characters)



value

: initial contents of the box



JavaScript code can access the contents as
document.BoxForm.userName.value

<html>


<!
-


COMP519 form06.html 13.10.2006
--
>




<head> <title> Fun with Text Boxes </title> </head>



<body>


<form name="
BoxForm
">


Enter your name here:


<input type="text" name="
userName
" id=“
userName

size
=“12”
value
="" />


<br /><br />


<input type="button" value="Click Me"


onclick="alert('Thanks, ' +
document.
BoxForm
.
userName
.
value

+


', I needed that.');" />


</form>


</body>

</html>

view page

Read/Write Text Boxes


similarly, can change the contents with an assignment

Note: the contents are raw text, no HTML formatting

Also: contents are accessed as a string, must
parseFloat
or

parseInt

if want a
number

<html>


<!
-


COMP519 form07.html 13.10.2006
--
>




<head>


<title> Fun with Text Boxes </title>


</head>



<body>


<form name="
BoxForm
">


Enter a number here:


<input type="text"
size
=“12” name="
number
"
value
=“2” />


<br /><br />


<input type="button" value="Double"


onclick="document.BoxForm.number.value=


parseFloat(document.
BoxForm
.
number
.
value
) * 2;" /
>


</form>


</body>

</html>

view page

Text Box Events


onchange
triggered when
the contents of
the box are
changed



onfocus


triggered when
the mouse clicks
in the box




blur()

removes focus

<html>


<!
-


COMP519 form08.html 13.10.2006
--
>




<head>


<title> Fun with Text Boxes </title>


<script type="text/javascript">


function FahrToCelsius(tempInFahr)


// Assumes: tempInFahr is a number (degrees Fahrenheit)


// Returns: corresponding temperature in degrees Celsius


{


return (5/9)*(tempInFahr
-

32);


}


</script>


</head>



<body>


<form name="BoxForm">


Temperature in Fahrenheit:


<input type="text" name="Fahr" size=“10” value=“0"


onchange
="document.BoxForm.Celsius.value =


FahrToCelsius(parseFloat(document.BoxForm.Fahr.value));"
/>


&nbsp; <tt>
----
></tt> &nbsp;


<input type="text" name="Celsius" size=“10” value=""


onfocus
="blur();"
/>


in Celsius


</form>


</body>

</html>

view page

Check buttons


<html>



<!
-


COMP519 form09.html 16.10.2008
--
>






<head>



<title> Check Boxes </title>




<script type="text/javascript">



function processCB()



{ var boxes = document.BoxForm.cb.length;



var s="";



for (var i = 0; i < boxes; i++)



{



if (document.BoxForm.cb[i].checked)



{ s = s + document.BoxForm.cb[i].value + " "; }



}



if (s == "") { s = "nothing"; }



alert("You selected " + s);



}



</script>



</head>




<body>



<form name="BoxForm">



Which of these things is unavoidable in life (select one or more):<br/><br/>



&nbsp; <input
type="checkbox"

name="cb" value="Death">Death</input><br/>



&nbsp; <input
type="checkbox"

name="cb" value="Taxes">Taxes</input><br/>



&nbsp; <input
type="checkbox"

name="cb" value="Robbie Williams">Robbie
Williams</input><br/>



<br/> <input type="button" value="Done" onclick="processCB()“ />



</form>



</body>


</html>

view page

Radio buttons


Radio buttons are similar to check boxes, but only one of them can be selected at
any time.



They are defined by <input type=“radio”> tags (similar to the checkbox tags in the
previous example, with similar properties) and accessed in the same manner.



JavaScript & Timeouts


the setTimeout function can be used to execute code at a later time


setTimeout(
JavaScriptCodeToBeExecuted
,
MillisecondsUntilExecution
)



example: forward link to a moved page

<html>


<!

-

COMP519 form13.html 13.10.2006
--
>




<head>


<title> Fun with Timeouts </title>


<script type="text/javascript">


function Move()


// Results: sets the current page contents to be newhome.html


{


self.location.href = "newhome.html";


}


</script>


</head>



<body
onload="setTimeout('
Move()
',
3000
);"
>


This page has moved to <a href="newhome.html">newhome.html</a>.


</body>

</html>

view page

Agenda


JavaScript and Client
-
side Programming


JavaScript elements


Event Handling and HTML forms




Review MS Access (creating tables, relationships, queries)


Lab session


Either work on Assignment 3 or practice JavaScript

MS Access



Relational Databases and Multi
-
table queries


Creating Tables


Creating relationships between tables


Querying the Database





Example file




Creating Tables


From the Create Tab

Enter data directly
into a table,
including the field
names

Enter field names,
data types and
descriptions in Table
Design View

Begin with a
template



When you create a new table is good practice to start
with the
Table Design
to enter field names, data types,
properties

Recap: Table Design View


Key symbol identifies primary key field

Set field properties in the

lower pane

Create Tables


Primary Key


Tables are automatically created with an AutoNumber field which
serves as the primary key


To change the primary key


Select a field
in Table Design View


Click the primary key icon

Primary Key
Field

Primary Key
icon

Create tables
-

Field Properties


Field Properties can be used to specify characteristics for individual
fields


Located in the lower pane of Table Design View

Field Size
property

Indexing

Recap: Datasheet View


Here you enter values in your table after you designed your table
in the Table Design View


Primary Key


a field that identifies each record as being unique

Primary Key

MS Access




Relational Databases and Multi
-
table queries


Creating Tables


Creating relationships between tables


Querying the Database



Tables Relationships


The strength of Access is the fact that it is a relational database


This means you can have multiple tables and create relationships between each
table


This helps eliminate redundant data

Relationship between two tables

Primary key

Foreign key

Foreign Key

Customer ID
-

Primary
Key in Customer Table

Customer ID

will only
appear in one record
-

there must only be one
unique id per customer

Customer ID
-

Regular
Field in Orders Table

Customer ID may appear
many times


one customer
can place many orders


Foreign key is used to establish relationships between tables


Based on the above example:


Customer Id is the foreign key in the Orders table


This is referred to as a One to Many Relationship

Establishing Relationships
-

Using the Relationship
Window


Click the Database tools and click the Relationships icon


First time of access will be empty and you need to add tables


Add the tables or queries from the Show table dialog box

Relationships icon

Show Table dialog
box

Relationship

window

Establishing Relationships



In the Relationship window, click and drag a field name from one table to a field
name in a related table

Click and drag to create a relationship

Establishing Relationships


Enter the appropriate settings in the Edit relationships dialog
box and click Create


A join line will appear when one table is joined to another

Infinity symbol notes referential
integrity has been applied

Set referential integrity and
cascades

MS Access




Relational Databases and Multi
-
table queries


Creating Tables


Creating relationships between tables


Querying the Database



Queries


Queries allow us to ask specific questions about data and
receive a record set back as answer


Typically you want to get a set of fields from multiple tables!


The record set that answers our question is called a dataset

Create Queries
-

Using Query Design View


From the Create Tab select Query Design from Other group


Two panes


the table pane and the design pane


Striking the F6 key will toggle you between sections

Tables
pane

Design
pane

Create Tab

Query


Searches
associated tables
and returns a
dataset that
matches the
query
parameters


Changes made
to the dataset will
be reflected in
the associated
tables

Specifying Criteria in a Query


Field row


displays the field name


Sort row


enables you to sort the dataset


Show row


controls whether or not you see a field in the dataset


Criteria row


determines the records that will be selected for display

Fields in design grid
allow us to specify
criteria for the dataset

Run a Query


Running, or executing, a query is done by clicking the Run command

Run command