Title: JavaScript 2
1JavaScript - 2
- The Document Object Model and more
- DOMs, Forms, creating documents on the fly
2The HTML-document
- JavaScript organises all elements on a web-page
into a hierarchy - Every element is seen as an object.
- Each object can have certain properties and
methods. - JavaScript can easily manipulate the objects
3HTML-document hierarchy
Example
To refer to the elements in JavaScript code
document.forms0.elements0.value
4Form Object Types
What to run when submit is pressed
ltFORM METHOD"POST" ACTION"mailtoemailname_at_emai
laddress"gt Surname ltINPUT TYPE"TEXT"
NAME"surname" gt ltBRgtltBRgt ltINPUT TYPE"submit"
NAME"Submit" VALUE"Submit"gt lt/FORMgt
5Blur ltINPUT TYPE"CHECKBOX" NAME"Popgrp"
VALUE"Blur"gt ltBRgt Five ltINPUT TYPE"CHECKBOX"
NAME"Popgrp" VALUE"Five"gt ltBRgt Steps ltINPUT
TYPE"CHECKBOX" NAME"Popgrp" VALUE"Steps"gt
Note the same name is given as this is one object
on the form
Male ltINPUT TYPE"RADIO" NAME"Gender"
VALUE"Male"gt Female ltINPUT TYPE"RADIO"
NAME"Gender" VALUE"Female"gt
6ltTEXTAREA NAME"comments" ROWS5 COLS20gt
lt/TEXTAREAgt
7Lists ltSELECTgt
ltSELECT NAME"Subjects" SIZE5 MULTIPLEgt
ltOPTIONgtEnglish Language ltOPTIONgtMathematics
ltOPTIONgtPhysics ltOPTIONgtHistory ltOPTIONgtArt
ltOPTIONgtChemistry lt/SELECTgt
8Some examples of JavaScript Objects
ltform action"http//osiris.sunderland.ac.uk/gun-s
cripts/survey.pl" namemyForm method"POST"gt
ltinput type"text" nameemail" size30gt
document.myForm.email.value
ltselect name"why"gt ltoption value0
selectedgtChoose one... ltoption value1gtIt was in
Sunderland ltoption value2gtIt looked
interesting ltoption value3gtIt was an uptodate
course ltoption value4gtMy parents made me ltoption
value5gtIt was the only offer I had ltoption
value6gtOther lt/selectgt
document.myForm.comments.value
document.myForm.why.value
lttextarea name"comments" rows5 cols70
wrap"VIRTUAL"gt lt/textareagt
9Forms, Function and JavaScript Example
lthtmlgt ltheadgt ltscript language"JavaScript"gt lt!--
hide function calculation() var
xparseFloat(document.calcu.numa.value) var
yparseFloat(document.calcu.numb.value) var
result x y alert(result) //
--gt lt/scriptgt lt/headgt ltbodygt lth3gtMy first
Calculatorlt/h3gt ltform name"calcu"gt Input A
ltinput type"text" name"numa" value""gt
ltbrgt Input B ltinput type"text" name"numb"
value""gt ltbrgt ltinput type"button"
value"Calculate" onClick"calculation()"gt lt/formgt
lt/bodygtlt/htmlgt
assignment
name of objects on form
10Data Conversion
On the last example we converted a string to a
real number
Using parseFloat(String)
Exercise The following all convert a string to
an Integer value of 10. What does the second
parameter represent ?
parseInt(A, 16) parseInt(12,
8) parseInt(1010, 2) parseInt(10, 10)
11Data Conversion
Answer The radix of the number e.g. the base of
the number system
Base 16
parseInt(A, 16) parseInt(12,
8) parseInt(1010, 2) parseInt(10, 10)
Base 8 (181210)
Base 2 (1804120110)
Base 10
There are number different data types and
conversion possible Refer to Netscapes reference
manual if in doubt ! Local version at
http//osiris.sunderland.ac.uk/cs0gun/com184/js/
index.htm
12Same Function better code !
Passing data to a function
lthtmlgt ltheadgt ltscript language"JavaScript"gt lt!--
hide function calculation(x,y) var result
parseFloat(x) parseFloat(y)
alert(result) // --gt lt/scriptgt lt/headgt ltbodygt lt
h3gtMy first Calculatorlt/h3gt ltform
name"calcu"gt Input A ltinput type"text"
name"numa" value""gt ltbrgt Input B ltinput
type"text" name"numb" value""gt ltbrgt ltinput
type"button" value"Calculate"
onClick"calculation(document.calcu.numa.value,
document.calcu.numb.value)"gt lt
/formgt lt/bodygtlt/htmlgt
13How is JavaScript used on the Web ?
- To create documents on-the-fly (client sided)
- creating and closing windows
- creating new documents
- Form validation (client sided)
- to reduce the load on servers by checking forms
prior to posting - To increase the functionality of the user
interface - improve the user interface e.g. Rollovers
14Creating documents on-the-fly
Example Opens a new Browser window without a
status bar, toolbar or menubar and then loads a
new page into the window
lthtmlgt ltheadgt ltscript language"JavaScript"gt
lt!-- hide function openWin2() myWin
window.open('http//osiris.sund.ac.uk/','new_windo
w_1', 'width400,height300,statusno,toolbarno,
menubarno') // --gt lt/scriptgt lt/headgt
ltbodygt ltformgt ltinput type"button"
value"Open New Window" onClick"openWin2()"gt lt/
formgt lt/bodygt lt/htmlgt
15Creating documents on-the-fly
When no file name is given, the result is a blank
document
function openWin3() myWin window.open('','new
_window_1','width400,height300, statusno,toolba
rno,menubarno') // open document for further
output myWin.document.open() // create
document myWin.document.write("lthtmlgtltheadgtlttitl
egtOn-the-fly") myWin.document.write("lt/titlegtlt/
headgtltbodygt") myWin.document.write("ltcentergtltfo
nt size3gt") myWin.document.write("This
HTML-document has been created ")
myWin.document.write("with the help of
JavaScript!") myWin.document.write("lt/fontgtlt/ce
ntergt") myWin.document.write("lt/bodygtlt/htmlgt")
// close the document - (not the window!)
myWin.document.close()
Using JavaScript to generate HTML
16StandardObjects
lthtmlgtltheadgt ltscript Language"JavaScript"gt lt!--
hide var timeStr, dateStr function clock()
now new Date() hours
now.getHours() minutes
now.getMinutes() seconds
now.getSeconds() timeStr ""
hours if (minutes lt 10) timeStr "0"
minutes else timeStr "" minutes if
(seconds lt 10) timeStr "0" seconds else
timeStr "" seconds document.clock.time.valu
e timeStr date
now.getDate() month now.getMonth()1
year now.getYear() dateStr ""
month if (date lt 10) dateStr "/0" date
else dateStr "/" date dateStr "/"
year document.clock.date.value
dateStr Timer setTimeout("clock()",1000
) // --gt lt/scriptgt lt/headgt ltbody
onLoad"clock()"gt ltform name"clock"gt Time
ltinput type"text" name"time" size"8"
value""gtltbrgt Date ltinput type"text"
name"date" size"8" value""gt lt/formgtlt/bodygtlt/htm
lgt
Use the actual time and date as a new one isnt
specified
The Date Object Returns the date and time
time
date
Rerun the function every 1000 msec
17Form validation (client sided)
- Can be used to
- Check that all parts of the form have been
completed - Check that certain characters exist
- e.g. checking for the _at_ symbol in email address
text input fields
18Form validation (client sided)
Example function
Test if the value is blank
function emailtest() if (document.myForm.email
.value "" document.myForm.email.value.ind
exof('_at_', 0) -1) alert("No valid
e-mail address!") else alert("OK!")
OR
Test if the value contains an _at_ symbol
19Form validation (client sided)
Checking a form before it is processed by a CGI
script
function validate() var formokay
true some if statements checking the form
fields (if any are invalid set the formokay to
false) return formokay ltform
onSubmitreturn validate()gt
The onSubmit event handler is used
20COMPLETE EXAMPLE
ltHTMLgt ltHEADgt ltTITLEgtFeedback Formlt/TITLEgt
ltscript language"JavaScript"gt lt!--
Hide function testemail(form) var emailok
true if (form.EMAIL.value ""
form.EMAIL.value.indexOf('_at_', 0) -1)
alert("No valid e-mail address!") emailokfals
e return emailok // --gt lt/scriptgt lt/HEADgt
ltBODYgt lth3gtFeedback formlt/h3gt ltFORM METHOD"POST"
NAME"feedback" ACTION"mailtogary.unthank_at_sunde
rland.ac.uk" onSubmit"return testemail(document.
feedback)"gt Please enter your comments about our
productltBRgt ltTEXTAREA NAME"comments" ROWS5
COLS20gtlt/TEXTAREAgt ltBRgtltBRgtPlease enter your
email addressltBRgt ltINPUT TYPE"TEXT" NAME"EMAIL"
gt ltBRgtltBRgt ltINPUT TYPE"submit" NAME"SUBMIT"
VALUE"Submit"gt lt/FORMgtlt/BODYgt lt/HTMLgt