Title: Document Objects Forms, Images and Links
1Document ObjectsForms, Images and Links
2Project 3
- To evaluation the expression, use
- var actual236
- parseFloat(eval(actual))
3Example
ltHTMLgt
ltheadgt
ltbodygt
lttitlegt
lth1gt
lth3gt
lth2gt
4Document model Javascript hierarchy
- Javascript document objects are arranged in a DOM
hierarchy. - The window object is at the top of the tree and
has child nodes - Navigator object
- Frame object
- History object
- Location object
- Document object
- Screen object
- Event object
5Document object
- Documents contain text, images, forms, links
- Subordinates to the document object are
- Anchors
- Images
- Forms
- Links
- Applets
- Embeds
6Dot syntax
- window.document.bgColor
- OR
- document.bgColor
7Document
- Every window contains a document object that
corresponds to the HTML document shown in the
window - The document object corresponds to the code
between ltbodygt lt/bodygt
8Document Properties
- activeElement
- alinkColor
- anchors
- applets
- bgColor
- cookie
- domain
- embeds
- fgColor
- forms
frames Height images lastModified linkColo
r links Location Referrer Title vlinkColor widt
h
9Document Methods
attachEvent() captureEvents() Clear() clearAttrib
utes() close() focus() getElementById() getElement
sByName() getElementsTagByName() getSelection() ha
ndleEvent()
hasFocus() open() recalc() releaseEvents() routeE
vent() setActive() write() writeln()
10Accessing Objects within a Document
The Document object contains many objects that
can be accessed using special arrays. For
example, collections of anchors, frames, images,
forms, and links can be accessed using these
array. The table below shows some of these
special arrays.
- anchorssubscript Reference named anchors in
a page. - appletssubscript Reference Java applets in a
page. - embedssubscript Reference embedded objects
in a page. - formssubscript Reference forms in a page.
- framessubscript Reference window objects of
frame objects in a page. - imagessubscript Reference images in a page.
- linkssubscript Reference hyper links in a
page.
11Form objects - Objectives
- Examine form objects
- Script push buttons and form submissions
- Manipulate checkboxes
- Work with radio buttons
- Check the options on a selection menu
- Validate the contents of text-related input fields
12Forms
- An HTML page may contain one or more forms. A
form is created with the ltformgtlt/formgt tags and
each set of form tags in an HTML document has an
associated form object. - Multiple forms are stored in an array by the
browser and can be referenced as shown in the
example below - document.forms0
- If the form has a name it can be referenced by
name as shown in the example below - document.formsmyForm
13Reset and Submit Methods
- The reset() method clears all of the components
of a form. - The submit() method is used to start the
processing of the form. Whatever action is
specified in the form will be executed when the
onsubmit event handler fires. - Form submission can be handled
- completely by a script
- submitting the forms contents to a server script
- using a script to pre-process the forms elements
before submitting it to a server
14Form ObjectProperties, Methods, and Events
Properties Methods Events
acceptCharset handleEvent() onreset
Action reset() onsubmit
autocomplete submit()
elementsi
encoding
enctype
Length
Method
Name
Target
15Form Object Properties
Property Value Type Description
acceptCharset String Read/Write The value assigned to the acceptCharset attribute of a form which is used to specify a list of one or more character sets that the server supports.
Action URL String Read/Write The value assigned to the action attribute of a form typically the URL to a CGI script or a mailto reference.
Autocomplete String Read/Write A value which determines whether autocomplete text can be used to fill in the contents of form fields as users enter values.
16Form Object Properties
Property Value Type Description
elements Array Read-only An array of all the form elements can be used to access form elements by their index. Supported by NN2, IE3 and later as well as Mozilla and Safari.
Encoding String Read/Write The value assigned to the enctype attribute of the form the encoding type for the form data. Deprecated in the W3C Document Object Model (DOM). Supported by NN2, IE3 and later as well as Mozilla and Safari.
17Form Object Properties (continued)
Property Value Type Description
enctype String Read/Write Same as encoding. This property is defined in the W3C DOM and is meant to replace the encoding property.
length Integer Read-only The number of elements in the form. Returns the same result as using the length property of the elements array.
method String Read/Write The value assigned to the method attribute of the form returns either GET or POST.
18Form Object Properties (continued)
Property Value Type Description
name String Read/Write The value assigned to the name attribute of the form the name of the form instance.
target String Read/Write The value assigned to the target attribute for the form or page typically the URL of the target page for the output of the form or the response from the server.
19Submitting a Form with Javascript
- Event handlers. Events are triggered by a user
when he initiates some actions (pressing a key,
clicking his mouse on a button, moving his mouse
over a link) - Handler can check the input data to decide
whether to submit or reject the form. - onclick
- onsubmit
- onreset
20Button ObjectProperties, Methods, and Events
Properties Methods Events
form click() onclick
name onmousedown
type onmouseup
value
If the form is not going to submit data to a
server, the button input type can be used
instead of the submit button
21Working With Push Buttons
- lthtmlgt
- ltheadgt
- lttitlegtPush buttonslt/titlegt
- ltscript type"text/javascript"gt
- function booktype(btn)
- if (btn.value "Mystery")
- alert("You selected mystery!")
-
- if (btn.value "Fantasy")
- alert("You selected fantasy!")
-
- if (btn.value "Science Fiction")
- alert("You selected science fiction!")
-
- if (btn.value "Romance")
- alert("You selected romance!")
-
22Working With Push Buttons(continued)
- var theOthers ""
- for (var i 0 i lt btn.form.elements.length
i) - if (btn.form.elementsi ! btn)
- theOthers btn.form.elementsi.value " "
-
-
- alert("You didn't select " theOthers)
-
- lt/scriptgt lt/headgt
- ltbodygt
- lth1gtWorking with Push Buttonslt/h1gt
- ltformgt
- ltpgtltbgtClick on your favorite book genres!lt/bgtlt/pgt
- ltinput type"button" value"Mystery"
onclick"booktype(this)" /gt - ltinput type"button" value"Fantasy"
onclick"booktype(this)" /gt - ltinput type"button" value"Science Fiction"
onclick"booktype(this)" /gt - ltinput type"button" value"Romance"
onclick"booktype(this)" /gt - lt/formgt
- lt/bodygt
23Checkbox Objects
- Checkboxes are commonly used in forms to make
boolean selections for example Member / Non
Member, Male / Female, etc.. - Adding a checkbox to an HTML document creates a
related checkbox object that can be accessed in
JavaScript.
24Checkbox ObjectProperties, Methods, and Events
Properties Methods Events
Checked click() onclick
Form
defaultChecked
Name
Type
Value
25Using and Validating Checkboxes
- ltscript type"text/javascript"gt
- function validcheck(x,y)
- var ischecked null
- var checkedItems
- for (var i x i lt y i)
- if (document.forms0.elementsi.checked)
- ischecked "ok"
- checkedItems checkedItems \n
document.forms0.elementsi.name -
-
- if (ischecked null)
- alert ("\nPlease select at least one of
the check boxes!\n\n Then resubmit the form.") -
- else
- alert(You have selected the following items
checkedItems) -
- return
-
- lt/scriptgt
26Using and Validating Checkboxes(continued)
- ltbodygt
- lth1gtScripting and Validating Checkboxeslt/h1gt
- ltform namemyform methodpost onsubmit"validcheck
(0,4)"gt - ltpgtSelect the topics you are interested in
- ltpgt
- ltinput typecheckbox name"biology" /gtBiologyltbr
/gt - ltinput typecheckbox name"calculus"
/gtCalculusltbr /gt - ltinput typecheckbox name"organic-chemistry"
/gtOrganic Chemistryltbr /gt - ltinput typecheckbox name"physics" /gtPhysicsltbr
/gt - ltinput typecheckbox name"world-literature"
/gtWorld Literaturelt/pgt - ltinput typesubmit value"Submit" /gt
- lt/formgt
- lt/bodygt
- lt/htmlgt
27Using Radio Button Objects
- Radio buttons are best used when the user should
make a single selection from a group of
selections. They are similar to checkboxes in
that they are selected or not selected, in other
words they store boolean values. However, unlike
checkboxes, you can only choose one radio button
at a time in a group of radio buttons. - Adding a radio button to an HTML document creates
a related radio button object that can be
accessed in JavaScript. - When creating an array of radio buttons, give
them all the same name.
28Using Radio Button Objects
- ltscript type"text/javascript"gt
- function checkbutton(radiogroup)
- for (var i 0 i lt radiogroup.length i)
- if (radiogroupi.checked)
- return i
-
-
- return 0
-
- function checkselection(form)
- var i checkbutton(form.group1)
- alert("You selected " form.group1i.value)
-
- lt/scriptgt
29Using Radio Button Objects(continued)
- ltbodygt
- ltformgt
- ltpgtSelect your favorite dessertlt/pgt
- ltpgtltinput typeradio namegroup1 value"none"
checked /gtNone - ltinput type"radio" name"group1" value"ice
cream" /gtIce cream - ltinput type"radio" name"group1" value"pie"
/gtFruit or cream pie - ltinput type"radio" name"group1" value"pudding"
/gtPudding or jello - ltinput type"radio" name"group1" value"candy
bar" /gtCandy barlt/pgt - ltpgtltinput typebutton value"Determine selection"
onclick"checkselection(this.form)" /gt - lt/formgt
- lt/bodygt
- lt/htmlgt
30Midterm exam
- JavaScript requires which of the following steps?
- a. Compile and deployment of the files.
- b. Edit and load into a Web browser.
- c. Edit and compile.
- d. All of the above
31Midterm exam
- In JavaScript, which of the following can be used
to indicate that comments end? - a. !--gt
- b. -- gt /
- c. !//--gt
- d. //!--gt
32Midterm exam
- Which of the following is a valid variable name?
- a. if
- b. var
- c. Weather
- d. All of the above
33Midterm exam
- How many times does the code within the body of
the for loop process for the following code if
"years" is equal to 3 (i1 iltyears i)
ltbody of the for loopgt ?? - a. 0
- b. 1
- c. 2
- d. 3
34Midterm exam
- How many times does the code within the
"while...loop" perform, if the "years" is 1
before this while loop and years is incremented
by 1 each iteration in the body of the while
loop - while (yearsgt0) ltbody of while loopgt?
- a. 0
- b. 1
- c. 2
- d. Endless Loop
35Midterm exam
- JavaScript pass variables by which of the
following? - a. By neither reference nor value
- b. By value
- c. By reference
- d. By value and reference
36Midterm exam
- A new array can be declared by which of the
following? - a. Student new Array
- b. Array new Student
- c. Student new Array ()
- d. Array new Student ()
37Midterm exam
- If the length of a String is determined to be 20
by using the length property, which of the
following is TRUE? - a. The index can vary from 0-19.
- b. The index can vary from 0-20.
- c. The index can vary from 1-19.
- d. The index can vary from 1-20.
38Midterm exam
- What is the possible number of different values
that can be returned from the getDay() method? - a. 0
- b. 7
- c. 31
- d. Unlimited
39Midterm exam
- Which of the following is the correct syntax to
use the Math Objects SQRT2 property? - a. Math.SQRT2
- b. Math.(SQRT2)
- c. MATH. SQRT2
- d. MATH.( SQRT2)
40Error
- ltscript language"JavaScriptgt
- document.writeln("Two,...")
- document.writeln( Three, ..")
- document.write("Four..ltbrgt")
- lt/scriptgt
41Code
- 17. function quote()
- var agedocument.quoteform.age.value
- if (agelt0)
- window.alert( Age must be gt0)
- else if (age gt 20 agelt30)
- alert(Your rate 2 a week)
- else if (agegt30 age lt40)
- alert(Your rate 3 a week)
- else if (agegt40 age lt50)
- alert(Your rate 5 a week)
- else if (age gt 50)
- alert(Your rate 10 a week)
- else if (age lt 20)
- alert(Undefined)
42Code
- 18. ltscript type"text/javascript"gt
- var answer document.form.input.value
- if (answer"Netscape" answer"netscape")
- alert("Congratulations")
- else alert("Sorry, it is not "answer)
- document.form.input.value""
- focument.form.input.focus()
-
43Code
- 19.
- function computeInterest(PMT,IR,NP)
- return (PMT (1-Math.pow(1IR,-1NP)/ IR)
44Code
- 20
- ltscript type"text/javascript"gt
- // Insert your code here
- var stringObj new String("Javascript is not
Java") - var index
- index stringObj.lastIndexOf("Java")
- document.write("Index of the second Java is
"index"ltBRgt") - document.write(stringObj.toUpperCase().fontcolor(
"red").bold().fontsize(10)) - lt/scriptgt
45Using Selection Objects
- Selection lists can be used for multiple
selections or for menus. Selection lists can be
helpful when you want to display a lot of
information in a small space. - All of the information in a selection list is
pre-validated by the author and does not have to
be validated by a script later. - Adding a selection list to an HTML document
creates a related - selection list object that can be accessed in
JavaScript.
46Selection ObjectProperties, Methods, and Events
Properties Methods Events
Form add() onchange
Length item()
Multiple namedItem()
Name optionsi.add()
optionsi optionsi.remove()
optionsi.defaultSelected remove()
optionsi.form
optionsi.index
optionsi.selected
optionsi.text
optionsi.value
selectedindex
Size
Type
Value
47Using Selection Menus
- ltscript type"text/javascript"gt
- function indexSelection(form)
- alert(form.userPref1.optionsform.userPref1.select
edIndex.text) -
- function directSelection(form)
- alert(form.userPref2.options.value)
-
- function multipleSelection(form)
- var theString ""
- for (var i 0 i lt form.userPref3.length i)
- if (form.userPref3.optionsi.selected)
- theString form.userPref3.optionsi.text "
\n" -
-
- alert("You have selected \n\n" theString)
-
48Using Selection Menus(continued)
- ltbodygt
- ltform name"form1"gt
- ltpgtChoose the language you plan on studyinglt/pgt
- ltpgtltselect name"userPref1"gt
- ltoption selected"selected"gtEnglishlt/optiongt
- ltoptiongtFrenchlt/optiongt
- ltoptiongtGermanlt/optiongt
- ltoptiongtSpanishlt/optiongt
- lt/selectgtlt/pgt
- ltpgtltinput type"button" value"Show Selection 1"
onclick"indexSelection(this.form)"/gtlt/pgt - lt/formgt
- ltform name"form2"gt
- ltpgtChoose one of the followinglt/pgt
- ltpgtltselect name"userPref2"gt
- ltoption value"Biology"gtBiologylt/optiongt
- ltoption value"Chemistry"gtChemistrylt/optiongt
- ltoption value"Physics"gtPhysicslt/optiongt
- ltoption value"EarthScience"gtEarth
Sciencelt/optiongt - lt/selectgtlt/pgt
49Using Selection Menus(continued)
- ltform name"form3"gt
- ltpgtChoose the areas of math you plan on
studyinglt/pgt - ltpgtltselect name"userPref3" multiple"multiple"gt
- ltoption value"Algebra"gtAlgebralt/optiongt
- ltoption value"Trigonometry"gtTrigonometrylt/optiongt
- ltoption value"Calculus"gtCalculuslt/optiongt
- ltoption value"DiscreteMath"gtDiscrete
Mathematicslt/optiongt - lt/selectgtlt/pgt
- ltpgtltinput type"button" value"Show Selection 3"
onclick"multipleSelection(this.form)"/gtlt/pgt - lt/formgt
- lt/bodygt
- lt/htmlgt
50Text Objects
- Text input fields are used to enter single lines
of text. Input text fields can have the following
styles - hidden the field does not show in the browser
window but text can be stored in it - password password fields display an
(asterisk) character for every character entered
into the text field - text text fields display the text entered by
the user - Text Area fields may contain multiple lines of
text and excellent choices when entering larger
amounts of text.
51Common Text Objects Methods
- blur() causes the text object to lose the focus
and deselects the object - focus() causes the object to gain the focus,
the text cursor appears in the field - select() selects the object, making it active
an object gains focus before it is selected and
active
52Text Objects Entry Restrictions
- You can restrict the data entered into text
fields based on the following categories - Letters allow or disallow the entry of
alphabetic characters - Numbers allow or disallow the entry of numeric
characters - Space - allow or disallow the entry of spaces
- Punctuation - allow or disallow the entry of
specific characters such as commas, periods or
hyphens
53Text ObjectProperties, Methods, and Events
Properties Methods Events
defaultValue blur() onafterupdate
form focus() onbeforeupdate
maxLength select() onblur
name onchange
readOnly onerrorupdate
size onfocus
type onselect
value
54Text Area ObjectProperties, Methods, and Events
Properties Methods Events
cols createTextRange() onafterupdate
defaultValue blur() onbeforeupdate
form focus() onblur
maxLength select() onchange
name onerrorupdate
readOnly onfocus
rows onselect
type
value
55Working with Text Objects
- lthtmlgt
- ltheadgt
- lttitlegtRegistrationlt/titlegt
- ltscript type"text/javascript"gt
- function validateinput(field,type)
- if (type "letters")
- var checkok "abcdefghijklmnopqrstuvwxyzabcdef
ghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" -
- if (type "numbers")
- var checkok "0123456789"
-
- if (type "lettersnumbers")
- var checkok "abcdefghijklmnopqrstuvwxyzabcdef
ghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123
456789" -
- if (type "special")
- var checkok "abcdefghijklmnopqrstuvwxyzabcdef
ghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123
456789 .,-" -
56Working with Text Objects(continued)
- var checkstr field.value
- var validok true
- for (i 0 i lt checkstr.length i)
- ch checkstr.charAt(i)
- for (j 0 j lt checkok.length j)
- if (ch checkok.charAt(j))
- break
-
- if (j checkok.length - 1)
- validok false
- break
-
-
-
- if (validok false)
- alert("The only valid characters for this
field are \n \n " checkok "\n \n Please go
back and change this field. Press ShiftTab") - return false
-
- return true
57Working with Text Objects(continued)
- ltbodygt
- lth2gtCustomer Registration Formlt/h2gt
- ltpgtPlease enter your name and addresslt/pgt
- ltformgt
- ltpgtFirst ltinput type"text" size"20"
name"firstname" onchange"validateinput(this,'let
ters')" /gt - MI ltinput type"text" size"1"
name"middleinitial" onchange"validateinput(this,
'letters')" /gt - Last ltinput type"text" size"20"
name"lastname" onchange"validateinput(this,'lett
ers')" /gtlt/pgt - ltpgtStreet address ltinput type"text" size"30"
name"streetaddress" onchange"validateinput(this,
'special')" /gtlt/pgt - ltpgtCity ltinput type"text" size"30"
name"cityaddress" onchange"validateinput(this,'l
etters')" /gtlt/pgt - ltpgtState/country ltinput type"text" size"30"
name"countryaddress" onchange"validateinput(this
,'letters')" /gtlt/pgt - ltpgtZipcode ltinput type"text" size"20"
name"zipcode" onchange"validateinput(this,'numbe
rs')" /gtlt/pgt - ltpgtltinput type"submit" value"submit" /gtlt/pgt
- lt/formgt
- lt/bodygt
- lt/htmlgt
58Summary
- Forms are important in acquiring information from
the user - Forms have form objects
- Fields have field objects
- The data entered into the form components (text
fields, selection lists, radio buttons, etc.) can
be validated on the client side using JavaScript
functions - Validating the data on the client side, before
sending the data to the server, can save time and
bandwidth - This processing also reduces errors
59Lab
- Step 1 lthtmlgt
- ltheadgt
- lttitlegt Week 7 Practice lt/titlegt
- // Enter your script here
- lt/headgt
- ltbodygt
- lth1gtWelcome to My Home Page!lt/h1gt
- // Enter your form here
- lt/bodygt
- lt/htmlgt
60Lab
- Step 2 insert in the body of this HTML document
two forms - - form 1 contains a textfield and a button
- - form 2 contains a textarea and a button
- Step 3 Write a script and insert it into ltheadgt
of this web page, to display the content of
textfield, and textarea (using alert or
document.write if a user presses/clicks the
corresponding button. - Step 4 Modify this script so that it allows only
letters and digits in the text field. - Step 4 Call this script from two forms,
respectively
61Lab
- Step 5 Modify the script so that it only allows
users to type in A-Z,a-z, and 0-9.
62Images
63Using Precaching to Swap Images
- JavaScript allows you to programatically
- change images
- create slide shows of images
- and display images based on time of day or year
- Rollovers can be achieved by swapping out images
that have been pre-cached. - Images that change based on a time interval or
season of the year can be created with
JavaScript.
64Image Objects
- To facilitate the swapping of images, you need to
create Image objects that can have a name and be
referenced in the scripts - For example
- var rolloverImage new Image()
- When referencing an image object you use the name
specified in the HTML code as shown below - ltimg srcrolloverOn.gif namemyRollovergt
- You should not confuse Image objects with the
ltimggt tags that are used by HTML code to display
an image
65Using the document.images Array
- JavaScript supports arrays of elements. When an
image is displayed using an HTML tag ltimggt the
browser builds an array of images. These images
can be accessed in one of two ways as shown
below - document.images0
- or
- document.imagesimageName where imageName is
the name of the image in the HTML code
66Using the document.images Array
- JavaScript code might use the syntax above in the
following manner - if(document.imagesrollOver.src
rollover.gif) - document.imagesrollOver.src
rolloff.gif -
- else
- document.imagesrollOver.src
rollover.gif -
67Common Properties
align Sets the alignment of the image the value assigned to the align attribute of an image. Accepted values are string constants absbottom, absmiddle, baseline, bottom, left, middle, right, texttop, and top. Supported by NN6, IE4 and later as well as Mozilla and Safari.
alt Sets the alternate text to display if the image cannot be displayed the value assigned to the alt attribute of an image. Supported by NN6, IE4 and later as well as Mozilla and Safari.
border Sets the size of the images border the value assigned to the border attribute of an image. Use border0 to hide the link border of an image placed within an a element. Supported by NN3, IE4 and later as well as Mozilla and Safari.
68Common Properties
complete Returns true when the lowsrc for an image finishes loading if no lowsrc is assigned, returns true when the source image finishes loading. Supported by NN3, IE4 and later as well as Mozilla and Safari.
height The value assigned to the height attribute of an image. Read/Write in IE4, NN5 or later. Read-only in IE3, NN4. Not supported by earlier versions of these browsers.
hspace The value assigned to the hspace attribute of an image. Read/Write in IE4, NN5 or later. Read-only in IE3, NN4. Not supported in earlier versions of these browsers.
lowsrc Sets a low-resolution source for an image the value assigned to the lowsrc attribute of an image. Supported by NN3, IE4 and later as well as Mozilla and Safari.
69Common Properties
name The value assigned to the name attribute of an image. Supported by NN2, IE3 and later as well as Mozilla and Safari.
src The value assigned to the src attribute of an image. Supported by NN3, IE4 and later as well as Mozilla and Safari.
vspace The value assigned to the vspace attribute of an image. Read/Write in IE4, NN5 or later. Read-only in IE3, NN4. Not supported by earlier versions of these browsers.
width The value assigned to the width attribute of an image. Read/Write in IE4, NN5 or later. Read-only in IE3, NN4. Not supported by earlier versions of these browsers.
70Precaching and Swapping Images
- Create an image object using the following
syntax - var Image1 new Image()
- Pre-caching occurs in two steps
- var Image1 new Image()
- Image1.src myImage.gif
71Rotating Images
- Updating images can be based on time events
- Updating images can also be based on the
interactions of the user
72Summary
- Images can be pre-loaded or cached to speed up
user interactivity for effects like rollovers - Images have properties and methods that can be
accessed - The document object contains an images array that
can be used to reference images in the document - Image objects can be created and accessed using
the name attribute of an image tag - Event handlers can be used to manage the changing
of image objects and their properties
73Lab
- Step 1 lthtmlgt
- ltheadgt
- lttitlegt Week 8 Practice lt/titlegt
- // Enter your script here
- lt/headgt
- ltbodygt
- lt! Insert your HTML code here --gt
- lt/bodygt
- lt/htmlgt
74Lab
- Step 2 Use google search engine (use image
search) to find 4 pictures for 4 seasons (Spring,
Summer, Fall, and Winter). Downloaded them. - Step 4 insert in the body of HTML code to do
display one picture (of your choice). - Step 5 precaching these pictures. Write a
function to randomly display the picture from the
above chosen picture on the left of your web page
whenever the user rolls a mouse over that picture - Step 6 change your HTML code to call this
function