The SELECT object invokes a function that does the job... A script in one of the documents is attempting to reference the selector object in one of the frames but the document has not fu
Trang 1<INPUT TYPE=”text” NAME=”convertor” VALUE=”sample”
onChange=”upperMe(this)”>
</FORM>
</BODY>
</HTML>
For Listing 9-2, the button invokes a function that communicates with a differ-ent elemdiffer-ent in the form Pass the form object
<HTML>
<HEAD>
<TITLE>Checkbox Inspector</TITLE>
<SCRIPT LANGUAGE=”JavaScript”>
function inspectBox(form) {
if (form.checkThis.checked) {
alert(“The box is checked.”) } else {
alert(“The box is not checked at the moment.”) }
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<INPUT TYPE=”checkbox” NAME=”checkThis”>Check here<BR>
<INPUT TYPE=”button” VALUE=”Inspect Box”
onClick=”inspectBox(this.form)”>
</FORM>
</BODY>
</HTML>
For Listing 9-3, again the button invokes a function that looks at other ele-ments in the form Pass the form object
<HTML>
<HEAD>
<TITLE>Extracting Highlighted Radio Button</TITLE>
<SCRIPT LANGUAGE=”JavaScript”>
function fullName(form) {
for (var i = 0; i < form.stooges.length; i++) {
if (form.stooges[i].checked) { break
} } alert(“You chose “ + form.stooges[i].value + “.”) }
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<B>Select your favorite Stooge:</B>
<INPUT TYPE=”radio” NAME=”stooges” VALUE=”Moe Howard”
CHECKED>Moe
Trang 2<INPUT TYPE=”radio” NAME=”stooges” VALUE=”Larry Fine”> Larry
<INPUT TYPE=”radio” NAME=”stooges” VALUE=”Curly Howard”>
Curly<BR>
<INPUT TYPE=”button” NAME=”Viewer” VALUE=”View Full Name ”
onClick=”fullName(this.form)”>
</FORM>
</BODY>
</HTML>
For Listing 9-4, all action is triggered by and confined to the SELECT object
Pass only that object to the function
<HTML>
<HEAD>
<TITLE>Select Navigation</TITLE>
<SCRIPT LANGUAGE=”JavaScript”>
function goThere(list) {
location = list.options[list.selectedIndex].value
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
Choose a place to go:
<SELECT NAME=”urlList” onChange=”goThere(this)”>
<OPTION SELECTED VALUE=”index.html”>Home Page
<OPTION VALUE=”store.html”>Shop Our Store
<OPTION VALUE=”policies.html”>Shipping Policies
<OPTION VALUE=”http://www.yahoo.com”>Search the Web
</SELECT>
</FORM>
</BODY>
</HTML>
2 This requires a bit of surgery The Submit button is replaced with a standard
button whose VALUEattribute is set to “Submit.” The button’s onClickevent
handler calls the checkForm()function, which performs the validation If an
empty field exists, the function must return to bail out of the loop Because
the event handler is not expecting any returned value, you can simply
issue the returnstatement to stop the function altogether If all the tests
pass, then the form is submitted with the submit()method Functions that
have a returnstatement inside an ifconstruction must also have a return
statement outside the construction so that it always returns a value
(includ-ing the nullvalue used here) The other change is that the onSubmitevent
handler has been removed from the <FORM>tag, because it is no longer
needed (the submit()method does not trigger an onSubmitevent handler)
<HTML>
<HEAD>
<TITLE>Validator</TITLE>
<SCRIPT LANGUAGE=”JavaScript”>
Trang 3function checkForm(form) { for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].value == “”) { alert(“Fill out ALL fields.”) return
} }
form.submit() return
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
Please enter all requested information:<BR>
First Name:<INPUT TYPE=”text” NAME=”firstName”><BR>
Last Name:<INPUT TYPE=”text” NAME=”lastName”><BR>
Rank:<INPUT TYPE=”text” NAME=”rank”><BR>
Serial Number:<INPUT TYPE=”text” NAME=”serialNumber”><BR>
<A HREF=”javascript:void checkForm(document.forms[0])”>
Submit Form</A>
</FORM>
</BODY>
</HTML>
3 The thiskeyword refers to the text field object, so that this.valuerefers to the valueproperty of that object
function showText(txt) { alert(txt)
}
4.document.accessories.acc1.value = “Leather Carrying Case” document.forms[1].acc1.value = “Leather Carrying Case”
5 The SELECT object invokes a function that does the job.
<HTML>
<HEAD>
<TITLE>Color Changer</TITLE>
<SCRIPT LANGUAGE=”JavaScript”>
function setColor(list) { var newColor = list.options[list.selectedIndex].value document.bgColor = newColor
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
Select a background color:
<SELECT onChange=”setColor(this)”>
<OPTION VALUE=”red”>Stop
<OPTION VALUE=”yellow”>Caution
<OPTION VALUE=”green”>Go
Trang 4</FORM>
</BODY>
</HTML>
Chapter 10 Answers
1 Use string.indexOf()to see if the field contains the “@” symbol
<HTML>
<HEAD>
<TITLE>E-mail Validator</TITLE>
<SCRIPT LANGUAGE=”JavaScript”>
function checkAddress(form) {
if (form.email.value.indexOf(“@”) == -1) { alert(“Check the e-mail address for accuracy.”) return false
} return true }
</SCRIPT>
</HEAD>
<BODY>
<FORM onSubmit=”return checkAddress(this)”>
Enter your e-mail address:
<INPUT TYPE=”text” NAME=”email” SIZE=30><BR>
<INPUT TYPE=”submit”>
</FORM>
</BODY>
</HTML>
2 Remember that the substring goes up to, but does not include, the index of
the second parameter Spaces count as characters
myString.substring(0,3) // result = “Net”
myString.substring(13,18) // result = “gator”
myString.substring(4,12) // result = “cape Nav”
3 The missing forloop is in boldface You could also use the increment
opera-tor on the countvariable (++count) to add 1 to it for each letter “e.”
function countE(form) {
var count = 0 var inputString = form.mainstring.value.toLowerCase()
for (var i = 0; i < inputString.length; i++) {
if (inputString.charAt(i) == “e”) { count += 1
} }
var msg = “The string has “ + count msg += “ instances of the letter e.”
alert(msg) }
Trang 54 The formula for the random throw of one die is in the chapter.
<HTML>
<HEAD>
<TITLE>E-mail Validator</TITLE>
<SCRIPT LANGUAGE=”JavaScript”>
function roll(form) { form.die1.value = Math.floor(Math.random() * 6) + 1 form.die2.value = Math.floor(Math.random() * 6) + 1 }
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<INPUT TYPE=”text” NAME=”die1” SIZE=2>
<INPUT TYPE=”text” NAME=”die2” SIZE=2><BR>
<INPUT TYPE=”button” VALUE=”Roll the Dice”
onClick=”roll(this.form)”>
</FORM>
</BODY>
</HTML>
5 If you used the Math.round()method in your calculations, that is fine for your current exposure to the Mathobject Another method, Math.ceil(), may be more valuable because it rounds up any fractional value
<HTML>
<HEAD>
<TITLE>Waiting for Santa</TITLE>
<SCRIPT LANGUAGE=”JavaScript”>
function daysToXMAS() { var oneDay = 1000 * 60 * 60 * 24 var today = new Date()
var XMAS = new Date(“December 25, 2001”) var diff = XMAS.getTime() - today.getTime() return Math.ceil(diff/oneDay)
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=”JavaScript”>
document.write(daysToXMAS() + “ days until Christmas.”)
</SCRIPT>
</BODY>
</HTML>
Trang 6Chapter 11 Answers
1.onLoad=”parent.currCourse = ‘history101’”
2.
3 All three frames are siblings, so references include the parent.
parent.mechanics.location.href = “french201M.html”
parent.description.location.href = “french201D.html”
4 A script in one of the documents is attempting to reference the selector
object in one of the frames but the document has not fully loaded, causing
the object to not yet be in the browser’s object model Rearrange the script so
that it fires in response to the onLoadevent handler of the framesetting
document
5 From the subwindow, the openerproperty refers back to the frame containing
the window.open()method To extend the reference to the frame’s parent,
the reference includes both pieces: opener.parent.ObjVarFuncName
Chapter 12 Answers
1 As the document loads, the <IMG>tag creates a document image object A
memory image object is created with the new Image()constructor Both
objects have the same properties, and assigning a URL to the srcproperty of
a memory object loads the image into the browser’s image cache
2.var janeImg = new Image(100,120)
janeImg.src = “jane.jpg”
3.document.images[“people”].src = janeImg.src
4 Surround <IMG>tags with link (A element) tags, and use the link’s onClick,
onMouseOver, and onMouseOutevent handlers Set the image’s BORDER
attribute to zero if you don’t want the link highlight to appear around the
image
Top Parent
<FRAMESET>
mechanics
<FRAME>
description
<FRAME>
navigation
<FRAME>
Trang 8JavaScript and
DOM Internet
Resources
As an online technology, JavaScript has plenty of support
online for scripters Items recommended here were
taken as a snapshot of Internet offerings in early 2001 But
beware! Sites change URLs change Be prepared to hunt
around for these items if the information provided here
becomes out-of-date by the time you read this
Support and Updates for this Book
The most up-to-date list of errata and other notes of
inter-est pertaining to this edition of the JavaScript Bible can be
found at the official Support Center, located at:
http://www.dannyg.com/update.html
If you are experiencing difficulty with the example listings
in this book, first check with the Support Center to see if your
question has been answered As mentioned earlier, you are
encouraged to enter the tutorial listings yourself to get used
to typing JavaScript (and HTML) code If, after copying the
examples from Part II, you can’t make something work (and a
fix hasn’t already been posted to the Support Center), send
the file you’ve typed to me via e-mail, along with a description
of what’s not working for you Also tell me the browser
version and operating system that you’re using My e-mail
address is dannyg@dannyg.com Regretfully, I am unable to
answer general questions about JavaScript or how to apply
examples from the book to your own projects
Newsgroups
The best places to get quick answers to your pressing
questions are online newsgroups Here are the top
JavaScript-related newsgroups:
D
Trang 9On most news servers:
comp.lang.javascript
On news://msnews.microsoft.com microsoft.public.scripting.jscript microsoft.public.windows.inetexplorer.ie5.programming.dhtml microsoft.public.windows.inetexplorer.ie5.programming.dhtml.scripting microsoft.public.inetsdk.programming.scripting.jscript
On news://secnews.netscape.com netscape.public.mozilla.dom
netscape.public.mozilla.jseng Before you post a question to a newsgroup, however, read about FAQs in the fol-lowing section and also use the extremely valuable Deja.com newsgroup archive, which is now owned by Google Look for links to “Usenet Advanced Search” at: http://groups.google.com
Enter the keyword or phrase into the top text box, but then also try to narrow your search by limiting the newsgroup(s) to search For example, if you have a question about weird behavior you are experiencing with the borderCollapse style property in IE, enter borderCollapseinto the keyword field, and then first try narrowing the search to the newsgroup comp.lang.javascript If you don’t find the answer there, try again with all the Microsoft newsgroups by specifying microsoft.public.*in the Newsgroups field
If you post a question to a newsgroup, you will most likely get a quick and intelligent response if you also provide either some sample code that’s giving you a problem, or a link to a temporary file on your server that others can check out Visualizing a problem you’ve spent days on is very hard for others Be as specific as possible, including the browser(s) on which the code must run and the nature of the problem
FAQs
One situation that arises with a popular and accessible technology, such as JavaScript and DHTML authoring, is that the same questions get asked over and over, as newcomers arrive on the scene daily Rather than invoke the ire of news-group users, look through existing FAQ files to see if your concern has already been raised and answered Here are some of the best JavaScript FAQ sites:
javascript.faqts.com developer.irt.org/script/script.htm For less-frequently asked questions — but previously asked and answered in a public form — use the dejanews.comarchive search, described earlier in this appendix
Trang 10Online Documentation
Locations of Web sites that dispense official documentation for one browser or
another are extremely fluid Therefore, the following information contains links only
to top-level areas of appropriate Web sites, along with tips on what to look for after
you are at the site
For Netscape browser technologies, start at:
http://developer.netscape.com/library/
You can also find some interesting future-oriented developer documentation at:
http://www.mozilla.org/docs
Microsoft has condensed its developer documentation into a massive site called
MSDN (Microsoft Developer Network) The place to begin is:
http://msdn.microsoft.com/workshop/
This page is the portal to many technologies, but the one most applicable to
JavaScript and client-side scripting is one labeled “DHTML, HTML & CSS” Look for
subject headers covering Document Object Model and DHTML References The
core JScript language is detailed in a separate section:
http://msdn.microsoft.com/scripting/jscript/techinfo/jsdocs.htm
Finally, you can read the industry standards for HTML, CSS, and ECMAScript
tech-nologies online Be aware that these documents are primarily intended for
develop-ers of tools that we use — browsdevelop-ers, WYSIWYG editors,and so forth — to direct them
on how their products should respond to tags, style sheets, scripts, and so on
Reading these documents has frequently been cited as a cure for insomnia
http://www.ecma.ch/ecma1/STAND/ECMA-262.HTM
http://www.w3.org/TR/html4
http://www.w3.org/TR/REC-CSS2
Please note that just because a particular item is described in an industry
stan-dard doesn’t mean that it is implemented in any or all browsers In the real world,
we must develop for the way the technologies are actually implemented in
browsers
World Wide Web
The number of Web sites devoted to JavaScript tips and tricks is mind-boggling
Many sites come and go in the middle of the night, leaving no trace of their former
existence If you are looking for more example code for applications not covered in
this book, perhaps the best place to begin your journey is through the traditional
search engines Narrowing your search through careful keyword choice is vital In
addition to the Netscape and (heavily Windows-oriented) Microsoft developer Web
sites (plus numerous online articles of mine listed at http://www.dannyg.com/
recentwriting.html), a couple other venerable sites are:
http://builder.com
http://www.webreference.com