File loading please wait...
Citation preview
Guide to HTML, JavaScript and PHP
DavidR.Brooks
Guide to HTML, JavaScript and PHP For Scientists and Engineers
DavidR.Brooks InstituteforEarthScienceResearchandEducation 2686OverhillDrive Eagleville,PA19403 USA [email protected]
ISBN978-0-85729-448-7 e-ISBN978-0-85729-449-4 DOI10.1007/978-0-85729-449-4 SpringerLondonDordrechtHeidelbergNewYork BritishLibraryCataloguinginPublicationData AcataloguerecordforthisbookisavailablefromtheBritishLibrary LibraryofCongressControlNumber:2011926229 ©Springer-VerlagLondonLimited2011 Apart from any fair dealing for the purposes of research or private study, or criticism or review, as permittedundertheCopyright,DesignsandPatentsAct1988,thispublicationmayonlybereproduced, storedortransmitted,inanyformorbyanymeans,withthepriorpermissioninwritingofthepublishers, or in the case of reprographic reproduction in accordance with the terms of licenses issued by the CopyrightLicensingAgency.Enquiriesconcerningreproductionoutsidethosetermsshouldbesentto thepublishers. Theuseofregisterednames,trademarks,etc.,inthispublicationdoesnotimply,evenintheabsenceof aspeciicstatement,thatsuchnamesareexemptfromtherelevantlawsandregulationsandtherefore freeforgeneraluse. Thepublishermakesnorepresentation,expressorimplied,withregardtotheaccuracyoftheinformation containedinthisbookandcannotacceptanylegalresponsibilityorliabilityforanyerrorsoromissions thatmaybemade. Printedonacid-freepaper SpringerispartofSpringerScience+BusinessMedia(www.springer.com)
Preface
“Thebestwaytobecomeacquaintedwithasubjectistowrite abookaboutit.” —BenjaminDisraeli “Each problem that I solved became a rule, which served afterwardstosolveotherproblems.” —RenéDescartes
i What Is the Purpose of This Book? Therearemanystudentsandprofessionalsinscienceandengineering,otherthanthosespeciicallyinterestedinieldssuchascomputerscienceorcomputerengineering,whoneedto knowhowtosolvecomputationalproblemsoncomputers.Therearebasicallytwoapproaches tomeetingtheneedsofsuchpeople.Oneistorelyonsoftwareapplicationssuchasspreadsheets, using built-in functions and perhaps user-deined macros, without requiring any explicitunderstandingoftheprinciplesonwhichprogramminglanguagesarebased. Asecondapproachistolearnaprogramminglanguage,previouslyFortranorPascal, and more recently C, C++, or Java. These languages are important for certain kinds of work,suchascomputerscienceorscientiiccomputing,buttheymaybeviewed,possibly withgoodreason,asirrelevantbymanystudentsandprofessionals. Fromastudent’spointofview,thereisnopainlesssolutiontothisdilemma,butinthis bookIassumethatlearningtosolvecomputationalproblemsinanonlineenvironment usingHTML,1JavaScript,andPHPwillatleastappeartobeamorerelevantapproach. HTMLandJavaScriptareuniversallyusedfordevelopingself-containedonlineapplications.TheuseofPHP for accessing externally stored data iles, a capability that is not availabledirectlythroughJavaScript,greatlyextendstherangeofscienceandengineering problemsthatcanbeaddressed.Aworkingknowledgeoftheseprogramminglanguagesis avaluableskillforanyscientistorengineer.ThefactthattheseareWeb-basedlanguages may make such skills more immediately marketable than comparable skills developed witholdertext-basedlanguages. 1
SeeGlossaryfordefinitionsoftermsappearinginboldfont.
v
vi
Preface
Insomeways,theHTML/JavaScript/PHPenvironmentismoredificulttolearnthana traditionaltext-basedprogramminglanguagesuchasC.Cisamature(somemightprefer “obsolete”),fairlysmalllanguagewithanunambiguoussetofsyntaxrulesandaprimitive text-basedinput/outputinterface.YoucanviewthelimitationsofCaseitherablessingor a curse, depending on your needs. A major advantage of C is that programs written in ANSIStandardCshouldworkequallywellonanycomputerthathasaCcompiler,making thelanguageinherentlyplatform-independent. HTML,JavaScript,andPHP,ontheotherhand,areimmatureandunstableprogramminglanguages(ifwecanagreetocallHTMLa“language”)thatfunctionwithinaconstantlychangingWebenvironment.TherearedialectsofHTMLandJavaScriptthatwill workonlyonparticularcomputingplatformsandthepossibilityexistsforlanguage“extensions”thatmaybeevenmoreplatform-dependent.PHPismoreplatform-independent,but itisstillanevolvinglanguagewhosestandardsaresetandmaintainedbyausergroup– essentiallybyvolunteers.WhileitistruethatthereareextensionstolanguagessuchasC andotherolderlanguagesthatareplatform-dependent,theplatformdependenceoflanguages used in the online environment is a major implementation issue rather than an occasionalminorinconvenience. Asoneindicationoftheteachingandlearningchallengestheseenvironmentsprovide, justthreepopularpaperbackHTMLandJavaScriptreferencebooksoccupynearly6in.of space(15cmindeferencetoametricaudience)onmyoficebookshelf!Agreatdealof thematerialinthosebooksisdevotedtoexplainingtheoftensubtledifferencesamong variousversionsofHTMLandJavaScript. Fortunately, it is possible to work with some core subsets of HTML and JavaScript which,withPHP,canbeusedtosolvesomeofthesamekindsofcomputationalproblems thatwouldbeappropriateforamoretraditionallanguagesuchasCorC++.Myinitial motivationforwritingthisbookwastolearnhowtouseHTML,JavaScript,andPHPto createmyownonlineapplications,andInowusethisenvironmentformanytasksthatI previouslywouldhaveundertakeninC.Basedonthisexperience,Ihaveconcludedthat, despite the fact that these languages cannot fairly be deined as “scientiic computing” languages,itisnonethelessentirelyreasonabletousethemtolearnbasicprogramming skills,andtocreateusefulandrobustscienceandengineeringapplications. Althoughthisbookisintendedfor“scientistsandengineers,”assuggestedbyitstitle, thecontentisnottechnicallycomplex.Theexamplesandexercisesdonotrequireextensive science, engineering, or mathematics background and only rarely is mathematics beyondbasicalgebraneeded.So,Ibelievethisbookcouldserveasabeginningprogrammingtextforundergraduatesandevenforhighschoolstudents.
ii Learning by Example Itiswellknownthatpeoplelearnnewskillsindifferentways.Personally,Ilearnbestby having a speciic goal and then studying examples that are related to that goal. Once I understandthoseexamples,Icanincorporatethemintomyownwork.Ihaveusedthat
Preface
vii
learningmodelinthisbook,whichcontainsmanycompleteexamplesthatcanserveas startingpointsforyourwork.(Seethesecondquotationatthebeginningofthispreface.) Thismodelworksparticularlywellinanonlineenvironment.Theamountofonline informationaboutHTML,JavaScript,andPHP,includingcodesamples,issovastthatit isonlyaslightexaggerationtostatethatnobodywritesoriginalcodeanymore.Ifyouhave trouble“learningbyexample,”youwillhavetroublelearningtheselanguages,notjust fromthisbook,butingeneralbecausethatishowmostoftheavailableinformationis presented. ItisaninescapablefactthatagreatdealofthesourcecodebehindWebpagesinvolves nothingmore(orless)thancreativecutting,pasting,andtweakingofexistingcode.Aside fromtheissuesofplagiarismandintellectualdishonestythatmustbedealtwithinanacademicenvironment,thereisalsothepracticalmatterofaneffectivelearningstrategy.You cannotlearntosolveyourowncomputationalproblemsjustbytryingtopastetogether someoneelse’swork.(Believeme,I’vetried!)Untilyoudevelopyourownindependent skills,youwillconstantlybefrustratedbecauseyouwillneverindexactlywhatyouneed tocopyandyouwillbeunabletosynthesizewhatyouneedfromwhatisavailable. So,whileyoushouldexpecttoindyourselfconstantlyrecyclingyourowncodebased onwhatyoulearnfromthisbook,youneedtomakesurethatyoureallylearnhowtouse theselanguagesanddon’tjustlearntocopy! Ifyouarereadingthisbook,youalmostcertainlyarenotanddonotaspiretobeaprofessionalprogrammer.Foracasualprogrammerfromascientiicortechnicalbackground, itcanbeverytimeconsumingtocutthroughtheclutterofonlineinformationaboutthese languageswhentheapplicationsarenotdirectlyapplicabletotheneedsofscientistsand engineers.Inmyownwork,whatIneedoverandoveragainissomesamplecodethatwill jogmymemoryabouthowtoapproachrecurringprogrammingproblems–howtoselect itemsfromapull-downlist,howtoextractinformationfromadataile,howtopassinformationfromanHTMLdocumenttoaPHPapplication,howtodisplaydata-basedgraphics,etc.Throughoutthebook,Ihavetriedtogiveexamplesthatservethisneed,including anentirechapterdevotedtoPHPgraphics.
iii The Origin and Uses of This Book In2007,SpringerpublishedAnIntroductiontoHTMLandJavaScriptforScientists andEngineers.Thiswasfollowedin2008byAnIntroductiontoPHPforScientistsand Engineers:BeyondJavaScript.ThosetwobooksfollowedthesequenceinwhichIlearned touseHTML,JavaScript,andPHPinmyownwork.(Seetheirstquotationatthebeginningofthispreface.)WhenthetimecametoconsiderasecondeditionoftheHTMLand JavaScriptbook,itseemedabetterideatoundertakearewritethatwouldcombineboth booksintoasinglevolume.Thisbookistheresult.Ihave,hopefully,clariiedsomeofthe explanations.TherearemoreexamplesandexercisesandIhaveaddedsomenewmaterial thatmystudentsandIhavefounduseful,includingabriefintroductiontousing“pseudocode”asanapproachtoorganizingsolutionstocomputingproblems(seeAppendix4).
viii
Preface
Ihaveusedbothoftheoriginalbooksastextsinan11-week(onequarter)introductory programmingcourseforbiomedicalengineeringgraduatestudentsatDrexelUniversity. IfoundthatacourserestrictedjusttoHTMLandJavaScriptisalittle“thin”forthisaudience.AddingabriefintroductiontoPHPsolvestheproblem.Thisbookeasilyprovides enough material for a one-semester introductory programming course for science and engineering students because the possibilities for PHP-based applications are limitless. Becauseofthebook’sveryspecificfocusonscienceandengineeringapplications, Ibelievethebookisalsoparticularlywellsuitedfordevelopingaworkingknowledgeof HTML, JavaScript, and PHP on your own if you are a student or professional in any technicalield.
iv Acknowledgments IamindebtedtoseveralclassesofgraduatestudentsfromDrexelUniversity’sSchoolof BiomedicalEngineering,Science&HealthSystems,whohaveprovidedfeedbackonthe materialinthisbookanditspredecessors.Iamalsoonceagainindebtedtomywife,Susan Caughlan,forherpatientandalwayshelpfulproofreadingofmymanuscripts. InstituteforEarthScienceResearchandEducation
DavidR.Brooks
Contents
1 IntroducingHTMLandJavaScript................................................................ 1 1.1 IntroducingtheTools................................................................................. 1 1.1.1 WhatIsanHTMLDocument?...................................................... 1 1.1.2 WhatIsJavaScript?........................................................................ 3 1.1.3 HowDoYouCreateHTML/JavaScriptDocuments?.................... 4 1.1.4 SomeTypographicConventionsUsedinThisBook..................... 6 1.1.5 WhereCanYouFindMoreInformationAboutHTML andJavaScript?.............................................................................. 6 1.2 YourFirstHTML/JavaScriptDocuments.................................................. 7 1.3 AccessingHTMLDocumentsontheWeb................................................. 14 1.4 AnotherExample....................................................................................... 16 2
HTMLDocumentBasics.................................................................................. 2.1 Documents,Elements,Attributes,andValues........................................... 2.1.1 EssentialElements......................................................................... 2.1.2 SomeOtherImportantElements.................................................... 2.2 HTMLSyntaxandStyle............................................................................ 2.3 UsingthescriptElement....................................................................... 2.4 CreatingandOrganizingaWebSite.......................................................... 2.5 SelectingandUsingColors........................................................................ 2.6 UsingCascadingStyleSheets.................................................................... 2.7 AnotherExample.......................................................................................
19 19 19 20 26 28 28 32 34 39
3
HTMLTables,Forms,Lists,andFrames....................................................... 3.1 ThetableElement.................................................................................. 3.1.1 BasicTableFormatting.................................................................. 3.1.2 SubdividingTablesintoSections................................................... 3.1.3 MergingCellsAcrossRowsandColumns.................................... 3.2 TheformandinputElements............................................................... 3.3 CreatingPull-DownLists........................................................................... 3.4 CombiningTablesandForms.................................................................... 3.5 E-MailingtheContentsofForms............................................................... 3.6 TheListElements......................................................................................
41 41 41 43 45 48 52 53 55 57
ix
x
Contents
3.7 3.8
UsingHTMLFrames............................................................................... MoreExamples......................................................................................... 3.8.1 SelectingCloudTypesfromaListofPossibilities.................... 3.8.2 ASimple“SplitWindow”Application......................................
62 67 67 69
4
FundamentalsoftheJavaScriptLanguage.................................................... 4.1 CapabilitiesofJavaScript......................................................................... 4.2 SomeEssentialTerminology.................................................................... 4.3 StructureofJavaScriptCode.................................................................... 4.3.1 JavaScriptStatements................................................................. 4.3.2 StatementBlocks........................................................................ 4.3.3 Comments................................................................................... 4.4 DataandObjects...................................................................................... 4.4.1 DataDeclarationsandVariables................................................. 4.4.2 DataTypes.................................................................................. 4.4.3 Literals........................................................................................ 4.4.4 CaseSensitivity.......................................................................... 4.4.5 ObjectsandMethodsforInputandOutput................................ 4.4.6 StringMethods........................................................................... 4.5 Tokens,Operators,Expressions,andStatements..................................... 4.5.1 Tokens......................................................................................... 4.5.2 ArithmeticOperators.................................................................. 4.5.3 TheAssignmentOperator........................................................... 4.5.4 ShorthandArithmetic/AssignmentOperators............................ 4.6 TheJavaScriptMathObject.................................................................... 4.7 ComparisonOperatorsandDecision-MakingStructures......................... 4.7.1 RelationalandLogicalOperators............................................... 4.7.2 TheifConstruct(BranchingStructures).................................. 4.7.3 TheswitchConstruct.............................................................. 4.8 LoopStructures........................................................................................ 4.8.1 Count-ControlledLoops............................................................. 4.8.2 ConditionalLoops...................................................................... 4.9 UsingJavaScripttoChangeValuesinFormFields................................. 4.10 MoreExamples......................................................................................... 4.10.1 SolvingtheQuadraticEquation.................................................. 4.10.2 RectangularRuleNumericalIntegration....................................
73 73 74 76 76 76 77 78 78 79 80 80 81 83 85 85 85 86 87 89 93 93 93 98 99 99 101 104 107 107 108
5
UsingArraysinHTML/JavaScript................................................................. 5.1 BasicArrayProperties.............................................................................. 5.2 SomeOperationsonArrays..................................................................... 5.2.1 ManipulatingStacksandQueues............................................... 5.2.2 Sorting........................................................................................ 5.3 MoreaboutArrayMethods...................................................................... 5.4 CreatingTwo-DimensionalArrays.......................................................... 5.5 UsingArraystoAccesstheContentsofForms.......................................
111 111 115 115 117 118 119 122
Contents
xi
122
5.5.1 Accessingvaluesoftype="text"Fields................................. 5.5.2 Accessingtype="radio"andtype="checkbox" Fields.............................................................................................. 5.5.3 AccessingMultipleOptionsChosenintags.............. 5.6 HidingtheContentsofaJavaScriptScript................................................ 5.7 MoreExamples.......................................................................................... 5.7.1 CheckingIDsandPasswords......................................................... 5.7.2 MagicSquares................................................................................
6
JavaScriptFunctions........................................................................................ 6.1 ThePurposeofFunctionsinProgramming............................................... 6.2 DeiningJavaScriptFunctions................................................................... 6.3 UsingJavaScriptFunctionsWithHTMLForms....................................... 6.3.1 PassingNumericalValuestoaFunction........................................ 6.3.2 UsingEntireFormsasInput.......................................................... 6.3.3 UsingArraystoReturnOutputValues.......................................... 6.4 SomeGlobalMethodsandEventHandlers............................................... 6.4.1 GlobalMethods.............................................................................. 6.4.2 UsingEventHandlerswithFormsandFunctions......................... 6.5 RecursiveFunctions................................................................................... 6.6 PassingValuesfromOneDocumenttoAnother....................................... 6.7 RevisitingtheJavaScriptsort()Methods............................................. 6.8 MoreExamples.......................................................................................... 6.8.1 DewpointTemperature................................................................... 6.8.2 LoanRepaymentSchedule............................................................ 6.8.3 LegendrePolynomials................................................................... 6.8.4 Array-DerivedPull-DownMenus.................................................. 6.8.5 Creatinga“Password-Protected”HTMLDocument.....................
135 135 136 138 139 142 145 146 146 149 150 154 157 158 158 160 162 163 165
7 CreatingaServer-SideEnvironmentwithPHP............................................. 7.1 GettingStartedwithPHP........................................................................... 7.2 MoreExamples.......................................................................................... 7.2.1 SolvingtheQuadraticEquation..................................................... 7.2.2 PreventingMultipleSubmissionsfromaForm.............................
167 167 182 182 184
8
187 187 188 203 206 206 211 221 222
WorkingwithPHP............................................................................................ 8.1 StructureofPHPScripts............................................................................ 8.1 CalculationswithPHP............................................................................... 8.3 MoreAboutPHPFileInput/Output........................................................... 8.4 MoreExamples.......................................................................................... 8.4.1 CalculatingVolumesofSolidObjects........................................... 8.4.2 Processing.bmpImageFiles........................................................ 8.4.3 TransformingandDisplayingImages............................................ 8.4.4 Self-ContainedHTML/JavaScript/PHPDocuments......................
125 127 129 131 131 132
xii
Contents
9
PHPArrays........................................................................................................ 9.1 ArrayDeinition....................................................................................... 9.2 ArraySorting............................................................................................ 9.3 Stacks,Queues,andLineCrashers.......................................................... 9.4 MoreExamples......................................................................................... 9.4.1 TheQuadraticFormulaRevisited.............................................. 9.4.2 ReadingcheckboxValues....................................................... 9.4.3 BuildingaHistogramArray....................................................... 9.4.4 ShufleaCardDeck.................................................................... 9.4.5 ManageaDataFile..................................................................... 9.4.6 RecursiveInsertionSort.............................................................
225 225 229 232 234 234 237 241 243 244 249
10
SummaryofSelectedPHPLanguageElements............................................. 10.1 DataTypesandOperators........................................................................ 10.1.1 DataTypes.................................................................................. 10.1.2 Operators.................................................................................... 10.2 ConditionalExecution.............................................................................. 10.2.1 ConditionalExecution................................................................ 10.2.2 Case-ControlledConditionalExecution..................................... 10.3 Loops........................................................................................................ 10.3.1 Count-ControlledLoops............................................................. 10.3.2 Condition-ControlledLoops....................................................... 10.4 FunctionsandLanguageConstructs......................................................... 10.4.1 FileHandlingandI/OFunctions................................................ 10.4.2 StringHandlingFunctions.......................................................... 10.4.3 MathConstantsandFunctions................................................... 10.4.4 ArrayFunctionsandLanguageConstructs................................ 10.4.5 MiscellaneousFunctionsandConstructs...................................
251 251 251 252 253 253 254 255 256 258 259 259 269 273 275 281
11 UsingPHPfromaCommandLine.................................................................. 287 12
UsingGraphicswithPHP................................................................................. 12.1 Introduction.............................................................................................. 12.2 WritingGDGraphicsApplicationsforDisplayingData......................... 12.2.1 GettingStarted............................................................................ 12.2.2 PieCharts.................................................................................... 12.2.3 HorizontalBarCharts................................................................. 12.2.4 VerticalBarCharts..................................................................... 12.2.5 LineGraphs................................................................................ 12.3 SummaryofSomeGDGraphicsFunctions............................................. 12.3.1 CreateandDestroyImages......................................................... 12.3.2 DrawLinesandShapes.............................................................. 12.3.3 DisplayText................................................................................
293 293 293 295 297 306 316 330 344 344 345 347
Contents
Appendices................................................................................................................. A.1 ListofDocumentExamples.............................................................................. A.2 DisplayingSpecialCharactersinanHTMLDocument................................... A.3 ASCIICharacterCodes..................................................................................... A.4 StrategiesforSolvingComputationalProblems...............................................
xiii
349 349 353 355 357
Exercises..................................................................................................................... 365 Glossary..................................................................................................................... 395 Index........................................................................................................................... 403 OutputExamplesinColor....................................................................................... 413
Introducing HTML and JavaScript
1
Abstract Chapter1providesaverybriefintroductiontousingHTMLandJavaScriptfor creating simple Web pages. It presents examples of how JavaScript interfaces with an HTMLdocumenttodisplaysomeprintedoutputinaWebbrowserwindow.Thechapter introduces the concept of an HTML document as an object, with certain methods and propertiesaccessiblethroughJavaScripttoactonthatobject. Numerous examples show how to modify the appearance of a document by using HTMLtagsandtheirattributes,includingaspartofatextstringpassedasacallingargumenttoJavaScript’swrite()method.
1.1 Introducing the Tools 1.1.1 What Is an HTML Document? HTMLisanacronymforHyperTextMarkupLanguage.HTMLdocuments,thefoundationofallcontentappearingontheWorldWideWeb(WWW),consistoftwoessentialparts:informationcontentandasetofinstructionsthattellsyourcomputerhowto displaythatcontent.Theinstructions—the“markup,”ineditorialjargon—comprisethe HTMLlanguage.Itisnotaprogramminglanguageinthetraditionalsense,butrathera setofinstructionsabouthowtodisplaycontent.Thecomputerapplicationthattranslates thisdescriptioniscalledaWebbrowser.Ideally,onlinecontentshouldlookthesame regardlessoftheoperatingsystemonwhichaWebbrowserresidesorthebrowserused. This goal of complete platform independence is achieved only approximately in practice. AbasicHTMLdocumentrequiresaminimumoffoursetsofelements: … … … … D.R.Brooks,GuidetoHTML,JavaScriptandPHP:ForScientistsandEngineers, DOI10.1007/978-0-85729-449-4_1,©Springer-VerlagLondonLimited2011
1
2
1
1
Introducing HTML and JavaScript
TheseelementsdeinetheessentialpartsofanHTMLdocument:thedocumentitself,a headingsection,atitlesection,andabody.Eachoftheelementsisdeinedbytwotags—a starttagandanendtag.Tagsarealwaysenclosedinanglebrackets:.Endtagsstart withaslash(/).Aswillbeshownlater,someHTMLelementshaveonlyonetag.Most tagsaresupposedtooccurinpairs,althoughthisruleisenforcedonlylooselyinHTML. InordertosupportascriptinglanguagesuchasJavaScript(muchmoreaboutthatlater!), anotherelementmustbeaddedtothefourbasicelements:
Asusedinthisbook,ascriptelementalwayscontainsJavaScriptcode. TheseelementsareorganizedasfollowswithinanHTMLdocument:
… …
A browser must be instructed to interpret certain parts of an HTML document as JavaScriptcode.Toaccomplishthis,alltextappearinginsidethescriptelementwill beinterpretedbyabrowserasoneormoreJavaScriptstatements.ThismeansthatHTML elementscannotappearinsidethescriptelement,becausethentheJavaScriptinterpreter would attempt (inappropriately) to interpret them as JavaScript code. This will generateaJavaScripterror.InDocument1.2,thetag,whichgeneratesaline break, is an HTML element, but it is included inside a quoted string of text. This is allowed,but document.write("Hello,world!"); document.write("It'sabeautifulday!"); isnot. Asnotedpreviously,JavaScriptisanobject-basedlanguage.Inprogrammingterminology,anHTMLdocumentisanobject.UsingJavaScript,predeinedmethodscanbeused toactonaspeciiedobject.(ObjectswillbediscussedinmoredetailstartinginChap.4.) Document1.2accesses(“calls”or“invokes”)thewrite()methodofthedocument objecttodisplaytext.Amethodisassociatedwithitsobjectbyusing“dotnotation,”asin document.write(). Methodssuchaswrite()often,butnotalways,requireoneormoreinputs,referred to as calling arguments. In Document 1.2, the text strings "Hello, world!" and "It's a beautiful day!";(enclosedinsingleordoublequotes)are
1.2 Your First HTML/JavaScript Documents
9
calling arguments for the write() method. Calling arguments provide the values on whichamethodacts. Asyouwillsee,mostHTMLelementsincludeattributesthatareusedtoassignpropertiestotheelement.Thescriptelementshouldincludevaluesforthelanguageand typeattributes,asshown:
AlthoughtheseHTMLcommenttagsappeartobeoutofplacebecauseHTMLelements can’tappearinsideascriptelement,abrowserthatdoessupportJavaScriptwillignore theHTMLcommenttagsthemselvesandabrowserthatdoesn’tsupportJavaScriptwill ignoreeverythinginsidethecommenttags. HTMLsyntaxiscase-insensitive,whichmeansthatisequivalentto or even . Some HTML document authors favor uppercase spellings for tags becausetheystandoutfromthetextcontent.However,XHTML(extendedHTML),the apparentsuccessortoHTML,requirestagstobeinlowercaseletters.4Hence,thistextwill
AlthoughthisbookadoptssomeXHTMLstylerules,thedocumentsarewritteninHTMLand arenotintendedtobefullyXHTML-compliant.
4
10
1
1
Introducing HTML and JavaScript
alwaysuselowercaselettersfortagnames.Notethat,despitepreviouswarningsthatile namesandcommandsarecase-sensitiveinsomesystems,browsersshouldnotbecasesensitive in their interpretation of HTML tags, regardless of the underlying operating system. JavaScriptsyntaxisalwayscase-sensitive,regardlessofthecomputersystemonwhichit runs,liketheC/C++languagesfromwhichitisderived.So,whenyouwriteJavaScriptcode, youneedtobeverycarefulaboutcase.Forexample,documentisanobjectnamerecognized byJavaScript,butDocumentisnot.(TrythisinDocument1.2ifyouneedconvincing.) NotethateachofthetwoJavaScriptstatements(thecallstodocument.write())is terminatedwithasemicolon.JavaScriptinterpretsasemicolonas“endofstatement.”As amatterofsyntax,alinefeedattheendofastatementwillalsobeinterpretedasmarking theendofthatstatement.However,itispoorprogrammingpracticetousethis“implied semicolon,” and all JavaScript statements appearing in this book should terminate withsemicolons.(Authorsarenotperfect!) YoucanmakeDocument1.2alittlefancierbyusingotherHTMLelementsandtheir attributestocontroltheappearanceofthetext.(Chap.2willpresentmuchmoreinformation aboutelementsandattributes.)InDocument1.3,font(fontdescription),h1(heading), andhr(horizontalrule)areelements,andcolor,size,andalignareattributes.Of theseelements,thehrelementrequiresonlyasingletagbecauseitdoesnotencloseany HTML content. Single-tag elements should include a forward slash at the end: ratherthan. Document1.3(HelloWorld2.htm)
Hello,world!
FirstJavaScript
(Trythisyourselftoseethecolorsdisplayed.)
1.2 Your First HTML/JavaScript Documents
11
As previously noted, there is no good reason to use JavaScript to display this ixed content,butDocument1.3againmakesthepointthatanyHTMLtagsappearingaspartof the calling argument passed to document.write()are treated as part of the text string—thecharactersenclosedinquotemarks—andthereforedon’tviolatetherulethat HTMLelementscan’tbeusedinsideascriptelement.TheHTMLtagsareessentially “pasted”intotheHTMLdocumentrightalongwiththetext.Withinthestring " It'sabeautifulday!" theattributevaluesareenclosedinsinglequotesratherthandoublequotes.Otherwise, it would not be clear where the quoted string begins and ends. Using double quotes inside a statement already enclosed in double quotes will generate a JavaScript error message. AnotherdifferencebetweenDocument1.2andDocument1.3isthat,in1.3,thescript elementisinsidethebodyelement.ThisisOK,althoughwewilloftentrytokeepthe scriptelementinsidetheheadelement,thusensuringthattheJavaScriptcodeisinterpretedbeforetherestofthepageisloaded.Thisdetailisofnoconcerninthisexample, whosesolepurposeistodisplaysometext. Asexpected,thisattemptedmodiicationofthescript,containingHTMLtagsinacontextwhereabrowserexpectstoseeonlyJavaScriptcode,willproduceanerror:
YoucanincludemorethanonescriptelementwithinanHTMLdocument,asshown inDocument1.4a,inwhichtherearetwoseparatescriptsections,arbitrarilydivided intoasectionabovethehorizontalrule(seethetag)andanotherbelowtherule. Document1.4a(HelloWorld3.htm)
Hello,world!(v.3)
FirstJavaScript
12
1
1
Introducing HTML and JavaScript
(SeeColorExample1forfull-coloroutput.) Document1.4acontainsananswertothisquestion:Howdoyoudisplaydoublequote markswiththe document.write() method if you can’t use double quotes inside a quotedstring?Theanswer:Usetheescapesequence".Escapesequencesalways startwithanampersand(&)andendwithasemicolon(;).Therearemanyescapesequences for displaying characters that are not available directly from the keyboard or would be misinterpreted by HTML if entered directly, and we will discuss them later as needed. AlistofcommonlyusedescapesequencesappearsinAppendix2. JavaScriptobjectshavepropertiesaswellasmethods.Likemethods,propertiesare associated with objects through the use of dot notation. One useful property of the documentobjectislastModiied,usedinDocument1.4a.Asitsnamesuggests,this property accesses the time and date stamp automatically stored along with a document wheneveritismodiiedandsaved,basedonthecalendarandclockonthecomputerused tocreatethedocument.Thisstampisautomaticallyattachedtothedocument,withoutany specialactionrequiredbythecreatorofthedocument.ThelastModiiedpropertyis usefulfordocumentsthatcontaintime-sensitiveinformation,orjusttogiveuserssome ideaofwhetherapagedisplayedinabrowseriscurrent. Document 1.4a contains these two statements that access two more document properties: document.write("background="+document.bgColor); document.write("font="+document.fgColor); Thesedisplayacodeforthebackgroundandfontcolors.
1.2 Your First HTML/JavaScript Documents
13
Attributes such as size and color have values. These values are supposed to be enclosedinquotes,althoughthisisnotactuallyrequiredinHTML.Quotesarerequiredin XHTMLandtheyarealwaysusedinthisbook.Youcanuseeitherdoubleorsinglequotes. In HTML documents, double quotes are generally accepted as the standard. However, whenHTMLelementswithattributesareincludedinsidequotedstrings,asin document.write("Hello,world!"); document.write(" Hesaid,"It'sabeautifulday!" "); thensinglequotesarerequiredforthevaluesinordertoavoidconlictwiththedouble quotesaroundthestring. AmorereasonableapproachtogeneratingtheoutputshownforDocument1.4ais touseJavaScriptonlyasrequiredtoaccessdesireddocumentproperties(andperhapsdisplaysomerelatedtext),anduseHTMLforeverythingelse.Document1.4bis amodiiedversionofDocument1.4awhichdoesthecontentformattingwithHTML tagsinsidethedocument.Thereisnoneedtoshowtheoutput,asitisidenticaltothat forDocument1.4a. Document1.4b(HelloWorld3HTML.htm)
Hello,world!(withHTML)
FirstJavaScript
Hello,world!
Hesaid,"It'sabeautifulday!""
14
1
1
Introducing HTML and JavaScript
Table 1.1 Some properties and methods of the document object Propertyormethod
Action
Property document.bgColor
Returnorsetcurrentvalueofbackground(page) color.Returns"#ffffff"for Returnorsetcurrentvalueoffontcolor.Returns "#0000ff"for Returntextstringcontainingdatethedocument waslastmodiied. Printquotedstringondocumentpage.
Property document.fgColor Property document.lastModiied Method document.write("Hello!") Method document.writeln("Hello!")
Printquotedstringondocumentpage,followedby linefeed.a
Because HTML ignores line feeds, the writeln() method will not normally produce any noticeabledifferenceinoutput.Ifthetexttobedisplayediswithinapreelement,thentheline feedwillbepresent. a
In this case, there is actually a justiication for putting one of the script sections insidethebodyofthedocument:Thisscriptisusedtodisplaycodesforthebackground andtextcolors,whichareknownonlyaftertheyaresetinsidethebodyelement. A summary of some properties and methods of the document object is given in Table1.1.ThebgColorandfgColorpropertieswilltellyouwhatthecurrentcolors are.Moreusefully,theycanalsobeusedtoassignthesecolors.Thismeansthatyoucan changefontandbackgroundcolors“onthely”whileaJavaScriptscriptisrunning.Note thatbgcolorisanHTMLattributeusedtosetthebackgroundcolorofthebodyelement andissupposedtobe(butdoesn’thavetobeincase-insensitiveHTML)spelledinlowercase letters. On the other hand, bgColor is a property of the JavaScript document objectandmustbespelledwithacapitalC,asshown. In Document 1.4b, the default background color has been set to light green and the defaulttextcolortomagentainsidethetag.Insertingthesetwolines: document.bgColor="red"; document.fgColor="black"; astheirsttwolinesinsidethe
OurNewHouse
Here'sthestatusofournewhouse.(Weknowyou're fascinated!)
Herearelinksto homeworkand
personaldocuments.
Document2.2b(resume.htm)
Resumé
Hereismyresumé.
Document2.2c(homework.htm)
Homework
Herearemyhomeworkproblems.
NotethatDocument2.2ausesforwardslashestoseparatethedirectoriesandtheile names.ThisisconsistentwithUNIXsyntax,butWindows/DOSsystemsusebackward slashes.ForwardslashesaretheHTMLstandard,andtheyshouldalwaysbeusedeven thoughbackwardslashesmayalsowork.AnotherpointofinterestisthatUNIXdirectory paths and ilenames are case-sensitive, but Windows paths and ilenames are not. This couldcauseproblemsifyoudevelopaWebpageonaWindows/DOScomputerandthen moveittoaUNIX-basedsystem.Asamatterofstyle,youshouldbeconsistentaboutcase indirectoryandilenamesevenwhenitappearsnottomatter.
32
2
2
HTML Document Basics
Asabriefdiversion,the“é”inresuméinDocument2.2bisproducedbyenteringthe escapesequenceé. InDocument2.2a,theabsolutereferencestoafolderonaparticularWindowscomputerdesktopareabadideabecausethisreferencewillneedtobechangediftheindex. htmileismovedtoadifferentplaceonthesamecomputer,ortoadifferentcomputer— forexample,toaUniversitydepartmentcomputerwithadifferentdirectory/folderstructure.Document2.2dshowsthepreferredsolution.Nowthepathstohomework.htmand resume.htm are given relative to the home folder, wherever the index2.htm ile resides.(Rememberthatthisile,nolongernamedindex.htm,willnotberecognizedas adefaulthomepage.)Thisdocumentassumesthatfoldershomeworkandpersonal existinthehomefolder.ThisrelativeURLshouldworkwithoutmodiicationwhenthe Websiteismovedtoadifferentcomputer.IftheWebsiteismoved,onlyasinglereference,totheindex2.htmile,needstobechanged. Document2.2d(index2.htm,anewversionofindex.htm)
MyPage
… | …
… | …
… Theattributesassociatedwiththesetagsallhavedefaultvalues,soyoudon’tneedtogive themvalues.Youcancreateatablewithoutusinganyattributesatallandthenaddattributesasneeded.InDocument3.1,theonlyspeciiedattributeisthebackgroundcolorin some cells. An easy way to familiarize yourself with the effects of specifying table attributesandtheirvaluesistoexperimentwithDocument3.1.
44
3
3
HTML Tables, Forms, Lists, and Frames
3.1.2 Subdividing Tables into Sections Thetbodyelementallowsatabletobedividedintotwoormoregroupsofrows.Each groupofrowsenclosedbya…tagcanhaveitsownattributesand can have a different predeined class attribute value. Document 3.2 shows a simple exampleinwhichrowsinatablearegroupedbybackgroundcolor. Document3.2(tbody.htm)
Usingthetbodyelement
Month | AverageTemperature °F |
January30.4 |
February | 33.0 |
March | 42.4 |
April | 52.4 |
May | 62.9 |
June | 71.8 |
July | 76.7 |
August | 75.5 |
September | 68.2 |
October | 56.4 |
3.1 The table Element
November | 46.4 |
December | 35.8 |
January–March and November–December usethe“cold”class,April–MayandSeptember– Octoberuse“cool,”andJune–Augustuse“hot.” Each class has a different background color. (Forthisgrayscalerenderingoftheoutput,gray, silver, and ivory have been chosen instead of somethingmorecolorful.)
3.1.3 Merging Cells Across Rows and Columns Ifyouarefamiliarwithcreatingtablesinaword processingapplication,youknowthatitiseasyto createmorecomplicatedtablelayoutsbymergingcellsacrossrowsandcolumns.Youcanalso dothiswithHTMLforms,usingthecolspan androwspanattributes.Document3.3showsa table that displays cloud names, altitudes, and whethertheyproduceprecipitationornot. Document3.3(cloudType.htm)
CloudTypeChart
CloudTypeChart
Altitude CloudName
High Cirrus
Cirrocumulus
Cirrostratus
Middle Altocumulus
Altostratus
45
46
3
3
HTML Tables, Forms, Lists, and Frames
Low Cumulus | nonprecipitating |
Altocumulus | nonprecipitating |
Stratocumulus | nonprecipitating |
Cumulonimbus | precipitating
Nimbostratus | precipitating
Itismuchmoretedioustomerge cellsacrossrowsincolumnsinan HTML table than it is in a word processor. You need to plan your tableinadvance,andeventhenyou should be prepared for some trial-and-errorediting! Here is a summary of some table-related elements and their attributes.Alltheelementsexcept table itself should appear only insideatableelement.
… Displaysthespeciiedtextasacaptionforatable.EarlierversionsofHTMLsupport only"top"(thedefaultvalue)or"bottom"forthevalueofthealignattribute. Somebrowsersmayallow"center"asavalueforalign,whichisworthnoting becausethismightoftenbethealignmentofchoiceforatablecaption. Attributes:align
Containstable-relatedandotherelements. Attributes:border,bordercolor,cellpadding,cellspacing,width … Groupsrowswithinthebodyofatablesoeachgroupcanbegivendifferentattributes andstyles. Attributes:align,char,charoff,valign (continued)
3.1 The table Element
47
(continued)
… | Deines data cells in the rows of a table. Does not contain other table-related elements. Attributes:align,bgcolor,char,charoff,colspan,nowrap,rowspan, width
… | Thethelementworksjustlikethetdelementexceptitautomaticallydisplaystext inboldfont,servingasheadingsfortablecolumns.Doesnotcontainotherelements. Attributes: align, bgcolor, char, charoff, colspan, nowrap, rowspan, valign,width
…
Deinesrowsinatable.Containstdorthelements. Attributes:align,bgcolor,valign Descriptionofattributes: align="…" Values:"left","right",or"center" Alignstexthorizontally.Whenalignisspeciiedinatrelement,itsvaluewillbe overriddenifitisspeciiedagainwithinatdelementinthatrow. bgcolor="…" Values:colornamesorhexadecimalvalues"#RRGGBB" Setsthebackgroundcolorforacellorrow.Whenbgcolorisspeciiedinatr element,itsvaluewillbeoverriddenifitisspeciiedagainwithinatdelementinthat row. border="…" Values:anintegernumberofpixels Addsabordertothetableanditscells.Avalueisoptional.Ifitisincluded,acolored (orgray,bydefault)borderisaddedaroundtheouterboundaryofthetable. bordercolor="…" Values:colornamesorhexadecimalvalues"#RRGGBB" Setsthecolorofatableborder. cellpadding="…" Values:anintegernumberofpixels Deinesverticalspacingbetweencellsinatable. cellspacing="…" Values:anintegernumberofpixels Deineshorizontalspacingbetweencellsinatable. colspan="…" Values:aninteger Deineshowmanycolumnsacellwillspan. (continued)
48
3
3
HTML Tables, Forms, Lists, and Frames
(continued) nowrap Prevents text from being automatically wrapped within a cell. It does not have a value. rowspan="…" Values:aninteger Deineshowmanyrowsacellwillspan. valign="…" Values:"top","middle",or"bottom" Alignstextvertically.Whenvalignisspeciiedinatrelement,itsvaluewillbe overriddenifitisspeciiedagainwithinatdelementinthatrow. width="…" Values:anumberorapercentage Speciiestableorcellwidthinpixels(width="140")orasapercentageofthe windowortableheaderwidth(width="80%").
3.2 The form and input Elements OneofthemostimportantapplicationsofHTMLdocumentsistoprovidetheWebpage equivalentofapaperform.Insomecases,aformjusthelpstoorganizeuserinputtoaWeb page.Often,anonlineformincludesprovisionsforsendingacompletedformbacktothe authoroftheWebpage.Inothercases,theformmayactasanI/Ointerfaceinwhichauser providesinputandtheWebpageprovidesresultsfromcalculationsorotheractions.Thisuse offormsisespeciallyimportantforthematerialpresentedinlaterchaptersofthisbook. HTMLformsaredeinedbytheformelement,usingstartandendtags:… tags.Theattributesoftheformelementare: action="…" Value:aprogrammer-suppliedURLthatidentiiesaprocessingscript,PHPilename, ormailto:followedbyane-mailaddress.Forexample, action="mailto:my_mail@my_univ.edu". enctype="…" Value: This book uses only enctype="text/plain". In combination with method="post", this will transmit form data with the name of the form ield followedbyan“=”signandthevalueoftheield.Thismakesiteasytointerpretthe contentsofaformthathasbeensubmitted. method="…" Values:"get","post" ThemethodattributecontrolshowdatafromaformissenttotheURL,PHPile, ore-mailaddressidentiiedintheactionattribute.Inthisbook,the"post"valueis usedbecauseitistheeasiestwaytotransmitformdatainaneasilyreadableformat. (continued)
3.2 The form and input Elements
49
(continued) name="…" Value:aprogrammer-selectednamethatisusedtoidentifytheform. Thenameattributeisneededonlyifadocumentcontainsmorethanoneform.
Table 3.1 Valuesfortheinputelement’stypeattribute Fieldtype
Description
type="button"
Providesaprogrammer-definedactiontobeassociatedwith thefieldthroughtheuseofaneventhandlersuchas onclick Allowsselectionofoneormorevaluesfromasetofpossible values Allowsthedeinitionoftextieldsthatcanbeaccessedby aJavaScriptscriptbutarenotdisplayedinadocument Allowsentryofcharacterdatabutdisplaysonlyasterisks Allowsselectionofoneandonlyonevaluefromasetof possiblevalues Usedtoresetallformieldstotheirdefaultvalues Processesformcontentsaccordingtomethodandaction Allowsentryofcharacterdata
type="checkbox" type="hidden" type="password" type="radio" type="reset" type="submit" type="text"
Formscontainoneormoreinputieldsidentiiedbytags.Becausethe inputelementdoesnotenclosecontent,ithasnoendtag,soitrequiresaclosingslash forXHTMLcompliance.Themostimportantattributeofinputisitstype.Thereare severalieldtypesthathavewell-deineddefaultbehaviorsinHTML.Thepossiblevalues arelistedinTable3.1. Thereisnoieldtypespeciicallyfornumericalvalues.Thiswillbesigniicantwhen JavaScriptisusedtoprocessthecontentsofforms.Theuseofeventhandlers,mentioned inthedescriptionofthe"button"ieldtype,willbediscussedinChaps.4and6. Hereisalistofattributesfortheinputelement.
checked Value:none Appliestotype="radio"andtype="checkbox"only. maxlength="…" Value:Maximumnumberofcharactersthatcanbeenteredintheield.Thisvaluecan begreaterthanthevaluegivenforthesizeattribute. name="…" Value:Aprogrammer-suppliednamefortheield.ThenameshouldfollowthevariablenamingconventionsforJavaScript(seeChap.4)inordertofacilitateitsuseinJavaScript scripts. (continued)
50
3
3
HTML Tables, Forms, Lists, and Frames
(continued) readonly Value:none Prevents ield values in type="text" or text="password" from being changed. size="…" Value:widthofthedisplayedield,incharacters. type="…" Values:SeeTable3.1. value="…" Value: a programmer-supplied default value that will be displayed in the ield. This value can be overridden by user input unless the readonly attribute is also speciied.
Theformelementtypicallycontainsacombinationofdocumenttextandinputields. Thedocumenttextcanbeusedtoexplaintotheuseroftheformwhatkindofinputis expected.Document3.4givesasimpleexamplethatusesseveralinputieldtypes: Document3.4(location.htm)
DataReportingSiteInformation
Pleaseenteryourlastname:
Pleaseenteryourlatitude:
N orS Pleaseenteryourlongitude:
EorW
Pleaseenteryourelevation: meters
3.2 The form and input Elements
51
Pleaseindicatetheseasonsduringwhichyoursitereports data: Winter: Spring: Summer: Fall:
Notethatsomeofthetextieldsareblankbecausenodefaultvalueattributehasbeen speciied.Theserequireuserinput,andthereisnowaytoestablishaheadoftimewhatthis inputmightbe.However,itmaystillbeworthwhileinsomecasestoprovideadefault valueifthatmighthelptheusertounderstandwhatisrequired.Whentheallowedinput choicescanbelimitedaheadoftimebythecreatorofthedocument,itisappropriatetouse radio buttons and checkboxes. You can create as many different combinations of these kindsofieldasyourapplicationneeds. Each group of radio and checkbox buttons has its own unique ield name and, withineachgroup,eachbuttonshouldhaveitsownvalue.InDocument3.4,therearetwo radiobuttongroups,namedNSandEW.Itisimportanttospecifyavalueforeachbutton, becausethevalueofthecheckedbuttonwillbecapturedwhenthecontentsoftheformare submittedtoarecipient’se-mailaddress.ThiswillbedemonstratedinthemodiiedversionofthisdocumentpresentedinSect.3.5.Defaultvaluesfortheradioieldcanbe speciiedbyusingthecheckedattribute.Whenyouaccessthedocument,thebuttonwith the checked attribute will be “on.” You can change it by clicking on another of the buttonsinthegroup. Thesamebasicrulesapplytocheckboxields.Youcanhavemorethanonegroupof checkboxes,eachwithitsuniquename.Theonlydifferenceisthatyoucanselectasmany boxesasyoulikewithineachgroup,ratherthanjustonevaluewithradioields.
52
3
3
HTML Tables, Forms, Lists, and Frames
3.3 Creating Pull-Down Lists A common feature on Web pages that use forms is a pull-down list. The select and optiontagsprovideanotherwaytolimittheinputchoicesausercanmakeonaform. Theimplementationdescribedhereissimilartoagroupofradiobuttonsinthesensethat onlyoneitemcanbeselectedfromalist.Thiscansimplifyadocumentinterfaceandeliminatetheneedforsomeinputcheckingthatmightotherwiseneedtobedoneifauserisfree totypewhateverhe/shelikesinaninputield.Forexample,creatingapull-downlistofthe monthsoftheyeareliminatestheneedforausertotype(andperhapstomistype)thename ofamonth,asshowninDocument3.5 Document3.5(select.htm)
Pull-DownList
Selectamonthfromthismenu:
January February March April May June July August September October November December
Intheoutputshown,theuserhaschosenthemonthofApril,whichisnowhighlighted. Thevaluesofthevalueattributecanbe,butdonothavetobe,thesameasthetextdisplayedforeachoption.Inthiscase,themonthvaluesarenumbersbetween1and12,rather thanthenamesofthemonths.Assigningtheselectedattributetotheirstoptionmeans that“January”willbehighlightedwhenthepull-downboxisirstdisplayed.Forlonger lists,thedefaultformatisforHTMLtoincludeascrollbaralongsidethelist.
3.4
Combining Tables and Forms
53
Althoughitiseasytocreatepull-down lists as well as groups of radio buttons andcheckboxes,asdescribedinSect.3.3, itisnotyetobvioushowadocumentwill makeuseoftheselectionsausermakes. AswillbeshowninChap.4,JavaScript providestherequiredcapabilities.
3.4 Combining Tables and Forms IntermsoforganizinganinteractiveWebpage,itisoftenhelpfultocreateoneormore tablesinwhichthecellcontentsareieldsinaform.Document3.6givesanexample. Document3.6(siteDeinition.htm)
ObservationSiteDescriptions
ObservationSite Descritions
Site# | SiteName | Latitude | Longitude | Elevation | Site1 | | | | | Site2 | 54
3
3
HTML Tables, Forms, Lists, and Frames
| | | | Site3 | | | | | Site4 | | | | | Site5 | | | | | 3.5
E-Mailing the Contents of Forms
55
Theoutputisshownwiththeoriginaldefaultieldnames,beforeauserstartstoadd newvalues. AlthoughitmayseemlikealotofworktocreateDocument3.6,thetaskisgreatly simpliiedbycopyingandpastinginformationfortherows.Whenyouaccessthispage, theTabkeymovesfromieldtoieldbutskipstheirstcolumn,whichisjustixedtext. Theuserofthepagecanchangethedefaultvaluesofalltheinputtextboxes.
3.5 E-Mailing the Contents of Forms Document3.4wouldbemuchmoreusefulifthelocationinformationprovidedbytheuser couldbesenttothecreatorofthedocument.Ingeneral,ifthebasicpurposeofformsisto provideaninteractiveinterfacebetweentheuserofaWebpageanditscreator,thereneeds to be a way to transmit the user-supplied information on a form back to the creator. RememberthatHTML/JavaScriptconstitutesapurelyclient-sideenvironment.However, itispossibletousetheformaction="mailto…"andmethodattributestosendthe contents of a form indirectly to the originator of the form (or some other speciied destination)byusingtheclientcomputer’se-mailutility. Inprinciple,thisiseasytodo,butthemethoddescribedhereisnotveryreliable.Itmay benecessaryirsttoresolveconlictsbetweenauser’sbrowserande-mailutilitywhich havenothingtodowiththecontentsoftheWebpageitself,oritmaysimplynotbepossibletogetthismethodtoworkacrosssomenetworksandplatforms. Hereishowtodirectthecontentsofaformtoaspeciiede-mailaddress,atleastin principle!
56
3
3
HTML Tables, Forms, Lists, and Frames
Document 3.7 is a modiication of Document 3.3 which allows a user to e-mail the contentsoftheformtoaspeciiedaddress. Document3.7(location2.htm)
Locationinformation
Pleaseenteryourlastname:
Pleaseenteryourlatitude:
N orS
Pleaseenteryourlongitude:
E orW
Pleaseenteryourelevation: meters
3.6 The List Elements
57
Afterenteringallvalues,theuserclicksonthelabeledsubmitbutton,andthecontents oftheformshouldbesenttothespeciiede-mailaddress.Inordertotrythisdocument, youmustinstallitonaWebpagewhereitcanbeaccessedonline.(Itwon’tworkifyoutry tosubmittheformlocallyfromanHTMLeditor,forexample.)Sometimes,thesubmit buttonmaynotactuallywork.Whenyouclickonthesubmitbutton,itmayappearthat thedatahavebeensent,butthee-mailneveractuallyarrives.Whenthishappens,theproblemliesnotwiththedocument,butwiththerelationshipbetweenyourbrowserandyour e-mailutility.Insomecases,itmaynotbepossibletosubmitformsinthiswayfromyour computer. Whentheformhasbeensubmittedsuccessfully,theieldnamesandvaluesarriveinthe body of an e-mail message. The example shown in the screen rendering produces this result: last_name=Brooks lat=40 NS=N lon=75 EW=W elevation=15 Thenamesaretheieldnamesgiveninthedocumentandthevaluesare,ofcourse,the valuesenteredbytheuser.
3.6 The List Elements Asshownearlierinthischapter,thetableandformelementsareusedastoolsfororganizing Web pages. List elements provide another way to impose formatting on related content.Table3.2givesabriefsummaryofthreekindsoflists.
Table 3.2 HTMLlistelements Description
HTMLtags
Use
Definition(orglossary)
…
Ordered
…
Unordered Listitem Glossaryhead Glossaryterm
… … …
Foralistthatincludesnames andextensivedescriptions Whenalistofthingsneedstobe numbered Foralistof“bulleted”items Createlistentryfor
or Createglossaryheadingfor Createglossarytermdescription for
58
3
3
HTML Tables, Forms, Lists, and Frames
Document3.8showshowtousetheselisttags. Document3.8(lists.htm)
UsingHTMLLists
Thispagedemonstratestheuseofunordered,ordered,and deinitionlists. - Useunorderedlistsfor"bulleted"items.
- Useorderedlistsfornumbereditems.
- Usedeinitionlistsforlistsofitemstobedeined.
HerearethreewaystoorganizecontentinanHTMLdocument:
- Useatable.
- Usealist.
- Use... tags.
Thisisawaytoproduceaneatlyformattedglossarylist.
deinitionlist () Usethistodisplayalistofglossaryitemsandtheir deinitions. orderedlist () Usethistodisplayanumberedlist. unorderedlist () Usethistodisplayalistofbulleteditems.
3.6 The List Elements
59
Theuseofthesetagsimposesapresetformatfordisplayinglistitems.Blanklinesare insertedbeforeandafterthelist,withnoor…
tagsrequiredtoseparate thelistsfromothertextinthedocument.Fororderedandunorderedlists,thelistitems themselves are indented. For the deinition list, the items are not indented, but the “deinitions” are. The contents of a list item can include text formatting elements. For example,inDocument3.8,theitemsinthedeinitionlistusethestrongelementtodisplaytheitemnameinaboldfont.Alistitemcanbeanimage,,or aURLreference,. Notetheuseoftodisplaythecharactersinthedocument. (Recallthatifyousimplyenterthesecharacters,theywillnotbedisplayedonthescreen becauseHTMLwilltrytoassociatethemwithtags.) Therearesomeattributesassociatedwithlistelementsthatprovidealittlemorecontrol overtheappearanceoflists.
60
3
3
HTML Tables, Forms, Lists, and Frames
start="n" Value:Theintegernspeciiesthestartingvalueofanorderedlist.Thedefaultvalueis start="1". type="…" Values:Forunorderedlists:"disc"(thedefaultvalue),"square","circle" Fororderedlists:"A"(uppercaseletters),"a"(lowercaseletters),"I"(uppercase Romanletters),"i"(lowercaseRomanletters),"1"(numbers,thedefaultvalue) value="n" Value:Theintegernspeciiesanumericalvalueforaniteminanorderedlistwhich overridesthedefaultvalue.Subsequentlistitemswillberenumberedstartingatthis value.
Finally,itispossibletocombinelisttypestocreatemorecomplicatedliststructures. Document 3.9 shows how list tags can be used to create the table of contents for a book. Document3.9(bookContents.htm)
TableofContentsforMyBook
TableofContentsforMyBook
- ChapterOne
- Section1.1
- FirstTopic
- SecondTopic
- subtopic1
- subtopic2
- Section1.2
- Section1.3
3.6 The List Elements
61
- ChapterTwo
- Section2.1
- FirstTopic
- SecondTopic
- Section2.2
- Section2.3
- ChapterThree
- Section3.1
- FirstTopic
- SecondTopic
- subtopic1
- subtopic2
- subtopic3
Section3.2 Section3.3 FirstTopic SecondTopic Section3.4 Notethatifthislistwereusedforanonlinebook,forexample,eachlistitemcould includealinktoaURLorahypertextlinktoanotherlocationwithinthesamedocument.
62
3
HTML Tables, Forms, Lists, and Frames
3
3.7 Using HTML Frames AnotherwayoforganizingcontentinHTMLdocumentsisthroughtheuseofframesto divideawindowintoseveralseparatelyaddressableblocksofcontent.Framesarebuilt usingtwoelements,frameandframeset. … Attributes: bordercolor, frameborder, marginheight, marginwidth, name,scrolling(yes,no,orauto),src Providesanameablewindowregion,asdeinedbytheframesetelement,witha linktothecontentofthatregion.Avalueforthesrcattributemustbegiven,butthe (continued)
3.7
Using HTML Frames
63
(continued) otherattributesareoptional.Thedefaultvalueforthescrollingattributeisauto, whichautomaticallyprovidesascrollbarifneededtodisplayallofawindow’scontent. … Attributes: border, bordercolor, cols, frameborder, framespacing, rows Providesspeciicationsfordividingawebpagewindowintotwoormoreseparately linkablesub-windows.Allattributesareoptionalexceptcolsandrows,whichmusthave valuesofnpixels,n%oftheavailablewindow,or*toilltheremainingwindowspace. Consider the following screen display. It is divided into three sections. The upper left-handcornercontainsaclickableimage.Thelowerleft-handcornercontainslinksto otherHTMLdocuments.Theright-handcolumnwillbeusedtodisplaythosedocuments. Whenthispageisirstaccessed,a“homepage”documentshouldbedisplayed.
Document3.10ashowstheirststepincreatingthispage. Document3.10a(frameMain.htm)
Asimpleframesetdocument
64
3
3
HTML Tables, Forms, Lists, and Frames
The frameset element is used to deine the frames. In this case, the window is dividedintotwocolumns.Theleft-handcolumnoccupies30%ofthepageandtherighthand column occupies the remaining 70%. (In the graphic displayed previously, the proportionslookdifferentbecausethescreendisplayhasbeencroppedtosavespace.) Theline
couldalsobewritten
where the asterisk is interpreted as “ill the remaining portion of the screen with the right-handcolumn.”Iftheframesizeisgivenasanumberwithoutthe%sign,itisinterpreted as pixels rather than a percentage of the full window. Setting this frame size to cols="200,*"willproducealeft-sideframethatisalways200pixelswide,regardless ofthescreenresolution. The left-hand column is further divided into two sub-windows. The top window occupiesthetop60%andthebottomwindowoccupiestheremaining40%.Eachwindow isassociatedwithaseparateHTMLdocument,frame1.htmandframe2.htm.These windowscouldbegivennames,buttheydon’thavetohavenames.Theright-handcolumn isassociatedwithanotherHTMLdocument,homeFrame.htm.This“homeframe”will be the destination for content that will be linked from the frame in the lower left-hand corner.Thisframeneedsanametoserveasa“target”fortheotherdocumentsthatwillbe displayed here. The name can be anything, but homeFrame is a self-explanatory and thereforereasonablechoice. Documents3.10b–dshowtheHTMLcodeforeachofthethreeframes. Document3.10b(homeFrame.htm)
MyHomeFrame
Homepagedisplaygoes here.
Document3.10c(frame1.htm)
TitleFrame
3.7
Using HTML Frames
65
Frames Demo
Document3.10d(frame2.htm)
GossipColumn
Linkstootherstuff… GossipColumn
PictureGallery home
Document3.10eistheHTMLdocumentreferencedinDocument3.10c. Document3.10e(frameDescription.htm)
Howthisimagewascreated.
ThisimagewascreatedinWindows'Paintprogram. Clickheretoreturn.
66
3
HTML Tables, Forms, Lists, and Frames
3
Document3.10d,forthelowerleft-handcorner,containslinkstoseveralotherdocuments, eachofwhichcanbedisplayedintheright-handwindow.Thisisdonebyusingthetarget attribute,whichlinkstohomeFrame,thenamevaluegiveninDocument3.10a: GossipColumn It is up to you to provide the gossip.htm and photoGallery.htm documents. Document3.10dalsoincludesalinkbacktothehomepagedocument.Theimageshown hereistheresultofclickingonthe“PictureGallery”linktoadocumentontheauthor’s computer;thepageimagehasbeencroppedtosavespace. Document310bcontainsthecodeforthehomeframethatisdisplayedwhenthepage is irst accessed. (The blink element, which causes text to blink on and off, will be ignoredbysomebrowsers.)Document3.10c,fortheupperleft-handframe,containsthe clickableimage,frame.gif,withaborderdrawnaroundit.Clickingontheimageopens a link to descriptive ile, frameDescription.htm (see Document 3.10e), to be providedbyyou.Thisdocumentwillbedisplayedinthe“FramesDemo”window(not openedinanewwindow)anditshouldcontainalinktoreturntoframe1.htm: Clickheretoreturn. HTMLframesprovideagreatdealoflexibilityfordisplayingcontent,butthereisone consequencethatmaynotbeimmediatelyobvious.Ifyoutrytheseexamplesonyourown computer, you will see that only the main frame document (frameMain.htm) is
3.8
More Examples
67
displayed as the URL link, regardless of which document is being displayed in the right-handcolumn.So,youcannotdirectlycopyorbookmarktheURLforaparticular document.Accessingthe“viewsource”optiononyourbrowserwilldisplaytheHTML codeonlyforframeMain.htm.Ifyouwishtobookmarkthe“picturegallery”page,for example,youcannotdosodirectly.Youcandisplaythepageseparatelybyaccessingthe documentseparately: http://.../photoGallery.htm butdoingthatassumesyoualreadyknowthenameandlocationofthisdocument. Thissituationdoesnotreallyhideallthecodeforthesedocuments.Youcanlookatthe frameMain.htm HTML code and then access separately the homeFrame.htm, frame1.htm,andframe2.htmdocumentstoexaminetheirHTMLcode.
3.8 More Examples 3.8.1 Selecting Cloud Types from a List of Possibilities Create a document that allows users to select observed cloud types from a list of p ossibilities.Morethanonecloudtypecanexistsimultaneously.Thecategoriesare: Highaltitude:Cirrus,Cirrocumulus,Cirrostratus Midaltitude:Altostratus,Altocumulus Lowaltitude:Stratus,Stratocumulus,Cumulus Precipitation-producing:Nimbostratus,Cumulonimbus Agoodwaytoorganizethisinformationistouseatablewithinaform.Theformields shouldbeoftypecheckboxratherthanradiobecausemultipleselectionsarepossible. ComparethisproblemwithDocument3.3,inwhichatablewasusedtodisplayjustthe cloudtypes. Document3.11(cloud1.htm)
CloudObservations
CloudObservations
CloudObservations(Selectasmanycloud typesasobserved.)
68
3
3
HTML Tables, Forms, Lists, and Frames
High | Cirrus | Cirrocumulus | Cirrostratus |
Middle | Altostratus | Altocumulus |
Low | Stratus | Stratocumulus | Cumulus |
Rain-Producing | 3.8 More Examples 69 Nimbostratus | Cumulonimbus |
InDocument3.11,checkboxesforthecloudtypesareorganizedintofourgroups,for high-,mid-,andlow-altitudeclouds,plusrain-producingclouds.Withineachgroup,each checkboxhasanameassociatedwithit.AswillbeshowninChap.5,thisarrangement makesitpossibleforJavaScriptto“poll”thecheckboxestoseewhichcloudsareobserved withineachgroup. NotethatthenamesgiventoeachcheckboxinDocument3.11arethesameasthetext enteredinthecorrespondingcell.Thisisonlybecausethesenamesandtextarereasonable descriptionsofthecellcontents.Ingeneral,thetextinthecelldoesnotneedtobethesame as,orevenrelatedto,thevalueofthenameattributeofthecheckbox.
3.8.2 A Simple "Split Window" Application Createanapplicationthatmaintainsoneormore“headerlines”acrossthetopofaWeb pagewindowwhilescrollingthroughalongtextdocument. Considerthisile: DRBWorcesterPA 40.178-75.3325 40305200 Mondayyr hr minsec EST PYR-1 7 1 20080 0 0 1 0.00031 7 1 20080 1 0 1.0006944440.00031 7 1 20080 2 0 1.0013888890.00031 …
PYR-2 T 0.0003120.198 0.0003120.174 0.0003120.174
70
3
3
HTML Tables, Forms, Lists, and Frames
Theilecontains1,440linesofdata(24htimes60minperhourforJuly1,2008)with thedateandtime,thedayandtimeconvertedtoafractionalEasternStandardTimeday (EST), data from two instruments, PYR-1 and PYR-2, and air temperature in degree Celsius. Foraileofthissize,itmightbeconvenienttobeabletodisplaythesedataundera ixedheaderthatidentiiesthecolumns,inthesamewaythatspreadsheetsallowcreation of a “split window.” Documents 3.12a, b show a very simple solution to this problem, usingHTMLframes. Document3.12a(pyranometerMain.htm)
Displaypyranometerdata
Document3.12b(header.htm)
Thisistheheader. mon day yr hr min sec EST PYR-1 PYR-2 T
3.8
More Examples
71
Theframesetrowsattributeallocatesthetop10%ofthepagetotheheaderandthe outputile,pyranometer.dat,isdisplayedintheremainderofthepage.Foradisplay thatistoolongtoitinonewindow,HTMLautomaticallycreatesascrollbardownthe right-hand sideofthewindow. A border has been retainedunderthe topframe, just to makeclearhowthepageisdivided,butitisoptional;toremovetheborder,settheframesetattributeborder="0". AsimplemodiicationoftheframesetcodeinDocument3.12awouldallowlisting anumberofdifferentilesinaleft-handcolumn,eachofwhichcouldbedisplayedinthe homepageframesimplybyclickingontheilename.Todothis,thedirectlinktopyranometer.datinDocument3.12awouldbereplacedwithanothernamespeciiedasthe valueofatargetattributeinthereferencetoeachdocumenttobedisplayed:
Notethatthepyranometer.datileisjustatab-delimitedtextile,notanHTML document.
Fundamentals of the JavaScript Language
4
Abstract Chapter4presentsthecoreprogrammingcapabilitiesofJavaScript.Thetopics includebasicprogramming terminology and concepts,code structure, data and objects, variables, operators, mathematical and string-manipulation functions, decision-making structures,andconstructsforrepetitivecalculations.
4.1 Capabilities of JavaScript Previous chapters have presented the features of HTML that provide the potential for interactingwithascriptinglanguagesuchasJavaScript.Inordertoworkinthisenvironment,youmustunderstandsomeofthefundamentalconceptsunderlyingprogramming languagesaswellasthedetailsofhowJavaScriptimplementstheseconcepts.Althoughan HTML document interface is still required to manage input and output in the HTML/ JavaScriptenvironment,thematerialinthischapterattemptstominimizethedetailsof interactionsbetweenJavaScriptandHTMLinfavorofpresentingprogrammingconcepts andtheirJavaScriptimplementationasdirectlyaspossible. JavaScriptsharescapabilitieswithotherlanguagessuchasC/C++.Ingeneral,whatare thecapabilitiesofthesekindsoflanguages?Whatkindsoftaskscanprogrammersexpect themtoperform?Hereisalist. 1. Manageinputandoutput. Tobeuseful,anylanguagemustprovideaninput/output(I/O)interfacewithauser. When a computer program is executed or a script is interpreted (in the case of JavaScript,asaresultofloadingaWebpageintoauser’sbrowser),theuserprovides input. The language instructs the user’s computer to perform tasks based on that input.Thelanguagetheninstructsthecomputertodisplaytheresults.Asimpleinterface(foratext-basedlanguagesuchasC,forexample)willacceptkeyboardinput anddisplaytextoutputonacomputermonitor.Asnotedseveraltimesinprevious chapters,HTMLandJavaScriptworktogethertoprovideanelegantanduniversal I/Ointerface.
D.R.Brooks,GuidetoHTML,JavaScriptandPHP:ForScientistsandEngineers, DOI10.1007/978-0-85729-449-4_4,©Springer-VerlagLondonLimited2011
73
74
4
4
Fundamentals of the JavaScript Language
2. Permitvaluestobemanipulatedinasymbolicway,independentofthewayaparticular computerstoresthatinformationinternally. Theessentialthrustofprogramminglanguagesistoprovideaname-basedsymbolic interfacebetweenacomputerandaprogrammer.Whenquantitiescanbegivennames insteadofmemoryaddresses,theycanthenbeaccessedandmanipulatedthroughthose namesratherthanrequiringaprogrammertokeeptrackofwherevaluesarestoredina computer’smemory. 3. Performarithmeticoperationsonnumbers. Ageneral-purposeprogramminglanguagemustincludearangeofarithmeticoperations onnumbers.AlthoughJavaScriptisnotintendedasa“number-crunching”languagefor seriousscientiiccomputing,itdoessupportmanyarithmeticoperationsandfunctions including,forexample,trigonometric,logarithmic,andexponentialfunctions.So,it is useful for a wide range of numerical calculations of interest in science and engineering. 4. Performoperationsoncharactersandstringsofcharacters. AgreatdealoftheworkJavaScriptisaskedtodoinvolvesmanipulatingcharactersand strings of characters rather than numbers. For example, JavaScript may be asked to compareanameprovidedasinputagainstapredeinedsetofnames.AnHTMLdocument is inherently character-based, so JavaScript must support the manipulation of charactersandstringsofcharacters,includinginterpretingstringsofcharactersasnumbers and vice versa. This is necessary because computers store numerical values in waysthatdifferfundamentallyfromthewaycharactersarestored. 5. Makedecisionsbasedoncomparingvalues. Computers cannot make decisions by “thinking” about multiple possibilities in a human-like way. However, they can compare values and act on the results of those comparisons.Typically,aprogramwillcomparevaluesandthenexecuteinstructions basedontheresultsofthosecomparisons.Inparticular,suchdecisionsareoftenembeddedinbranchingstructuresthatexecuteonesetofinstructionstotheexclusionof others,basedonacomparisonofvalues. 6. Performrepetitivecalculations. Loopstructuresareusedtoallowcomputerstoperformrepetitivecalculations.These calculationsmaybeterminatedaftertheyhavebeenexecutedaspeciiednumberoftimes, ortheymaybeexecutedonlyuntilorwhilesomesetofconditionsissatisied.
4.2 Some Essential Terminology Theterminologyofprogramminglanguagescanbeconfusing.Nonetheless,itisessentialtoagreeuponthemeaninganduseoftermsinordertodiscussprogrammingconcepts, especially because the programming-speciic meaning of some terms must be
4.2
Some Essential Terminology
75
Table 4.1 Deinitionsofsomeessentialprogramminglanguageterms Term
DeinitionsandExamples
expression
Agroupoftokensthatcanbeevaluatedaspartofastatementtoyield aresult. y+z "Thisisastring." Thenameassociatedwithavariable,object,orfunction. Anyallowedname,e.g.,x,getArea,my_name,withoutembedded spaces. Awordthatispartofalanguageandhasaspeciicmeaning.Keywords cannotbeusedasidentiiers. function,var,for Avalue(asopposedtoanidentiier)embeddedinascript. 3.14159 "Here'sastring." Asymbolthatrepresentsamathematicalorotheroperation. =,+,-,*,/,% Loosely,aseriesofstatementsoracompiledequivalent.InJavaScript,a “program”isbetterreferredtoasascript.Scriptsareinterpretedone lineatatime,notcompiled. Awordthatmightbecomepartofalanguage.Reservedwordsshould notbeusedasidentiiers. class,const AseriesofstatementswritteninJavaScriptorsomeotherscripting language. Acommandthatchangesthestatusofaprogramasitexecutes,by deiningvariables,changingthevalueofavariable,ormodifying theorderinwhichotherstatementsareexecuted. x=y+z; area=Math.PI*radius*radius; Anindivisiblelexicalunitdeinedwithinaprogramminglanguage. Allvariables,keywords,operators,andliterals. Aplaceinmemorythatholdsdataandisrepresentedbyaunique identiier. (see“identiier”)
identiier
keyword
literal
operator program
reservedword
script statement
token variable
distinguished from their everyday conversational use. Table 4.1 gives some essential termsandtheirdeinitions. ThesetermsdeinethebuildingblocksofaJavaScriptscript,startingwithtokens: tokens(identiiers,keywords,literals,operators)→expressions→statements→script Individualtokensformexpressions.Expressionsformstatements.Ascriptconsistsofa collectionofstatements.
76
4
4
Fundamentals of the JavaScript Language
4.3 Structure of JavaScript Code 4.3.1 JavaScript Statements InstructionsinJavaScriptareconveyedthroughaseriesofstatements.Asindicatedinthe previoussection,statementsarebuiltfromexpressionsconsistingoftokens.Tobegina statement,simplystarttypingsomethingthatfollowsthesyntaxrulesofJavaScript.When it is time to terminate a programming language statement, there are two choices. One choiceistopresstheEnterorReturnkeyonyourcomputer.Thiswillterminateboththe physicallineandthestatement.Thismeansthateachphysicallinecancontainnomore thanonestatement.(Itcouldbeablanklinewithnostatementatall.)Thesecondchoiceis touseauniqueterminatingcharactertomarktheendofastatement. As a matter of syntax, JavaScript allows both these choices. An “end of line” mark (createdbypushingtheEnterorReturnkey)willmarktheendofastatement.Because ofJavaScript’srootsinC/C++,thepreferredsyntaxistoterminateeachstatementwitha semicolon.Inthisbook,JavaScriptstatementswillalwaysbeterminatedwithasemicolon. Asabonus,thisstylechoiceallowsmultiplestatementstoappearonthesameline. AsetofJavaScriptstatementsiscalledascript.Presumably,thegoalofascriptistodo somethinguseful.So,theimplicationofcallingsomethinga“script”isthatitcontainsall theinstructionsrequiredtocompleteaspeciictask.AsnotedinChap.1,eventhesimplest texteditorcanbeusedtocreateascript,whichisnothingmorethanatextdocument.But, aswasthecaseforcreatingHTMLdocuments,itwillbeeasiertocreateJavaScriptscripts withaneditorintendedforthispurpose. JavaScriptisafree-formatlanguage.Thismeansthatstatementscanappearanywhere onaline.Aslongasyouterminateeachstatementwithasemicolon,youcanevenput multiplestatementsonasingleline.Thislexibilityissupposedtoencouragethewriting ofcodethatislogicallyorganizedandeasytoread.Goodprogrammersalwaysadopta consistentapproachtothelayoutoftheircode.Hopefully,theexamplesinthisbookwill point the way to producing easily readable code. See Appendix 4 for a “pseudocode” approachtodesigningaccurateandreadablecode.
4.3.2 Statement Blocks Often,severalcodestatementsaregroupedtogetherinastatementblock.Theseblocks beginandendwithcurlybrackets: { }
{statementsgohere}
Laterinthischapter,therewillbeseveralexamplesofhowtousestatementblocks.
4.3
Structure of JavaScript Code
77
4.3.3 Comments Comments are an essential part of good programming style, no matter what the language.Commentsareinsertedintocodebyusingcertaincombinationsofcharacters that will always be interpreted unambiguously as marking the beginning or end of a comment. JavaScript supports two kinds of comments: single- and multiple-line comments.Youcanuseeitherorbothofthesecommentformatswithinthesamescript. However,theycannotbemixedinthesamecomment.Also,youcannothave“nested” multiple-linecomments: //Thisisasingle-linecomment. /*This isa multiple-line comment. */ /*Thiscode /*willgenerateasyntaxerror!*/ */ Because a JavaScript interpreter ignores comments when it executes statements, c ommentscanoccuronseparatelinesoronthesamelineasastatement.Commentsstarted withadoubleslashcannotbeplacedatthebeginningofastatementbecauseJavaScript hasnowayofknowingwherethecommentendsandthecodebegins.Thiscodewillwork becausethereisan(invisible)“return”characterattheendofthelinethatisinterpretedas theendofthecomment: //Thegravitationalconstantis varg=9.8;//m/s^2 Thiswillnotwork //Thegravitationalconstantisvarg=9.8;//m/s^2 butthiswill: /*Thegravitationalconstantis*/varg=9.8;//m/s^2 Itiseasytooverlooktheimportanceofincludingcommentsinyourcode.Intelligently commentedcodeiseasiertounderstand,bothforyouwhenyoureturntoitatalaterdate andforotherswhoneedtoexamineyourcode.Ifyoudon’tdevelopthehabitofincluding commentsinallyourcode,eventuallyyouwillbesorry!
78
4
4
Fundamentals of the JavaScript Language
4.4 Data and Objects Ingeneral,programminglanguagescanworkwithdifferentkindsofinformation.Each kindofinformationisassociatedwithadatatype.Eachdatatypeisstoreddifferently withintheprogrammingenvironment,andeachisassociatedwithaspeciicsetofoperations.Forexample,itisobviousthatyoucanaddtwonumbers(3.3+12.9),butitis lessobviouswhat(ifanything)itmeanstoassociateanadditionoperationwithcharacter literals('A'+'c').Inthelattercase,Aandcarenotbeingusedassymbolicnames, butasthe“literalvalues”ofthecharacters'A'and'c'. A concept central to all high-level programming languages is that discrete units of informationcalledvariablescanbeassociatedwithspeciiclocationsincomputermemory. Variablesserveas“containers”fordata.Adatacontainerisestablishedbygivingitasymbolicname,calledanidentiier.Thisprocessiscalleddatadeclaration.Onceidentiiers havebeenestablishedwithmeaningfulnames,youcanwritecodetomanipulateinformation symbolicallybyusingtheidentiiernames,therebyfreeingyoufromhavingtothinkdirectly about where information is actually stored in your computer’s memory. (As a practical matter,youcan’tigureoutexactlywherethisinformationisstoredevenifyouthinkyou need to know.) This symbolic approach makes it possible to write scripts that will work withoutmodiicationonanycomputerwithaWebbrowserthatsupportsJavaScript.
4.4.1 Data Declarations and Variables Abasicprogrammingrule,nomatterwhatthelanguage,isthatvariablesmustbedeclared before they are used elsewhere in a program. Data declaration assigns an identiier (avariablename)toadatacontainerandassociatestheidentiierwithaparticularlocation inyourcomputer’smemory.Theallocationofmemoryishandledbytheprogramming environment(inthiscase,yourbrowseranditsJavaScriptinterpreter)andisofnoconcern toyouasaprogrammer. The data declaration process, whether explicit or implicit, is required to enable a programmingenvironmenttomanageitsmemoryresourcesandperformappropriateoperations.InJavaScript,thekeywordvarisusedtodeclarevariablesandtheiridentiiers. Considerthiscode: varg; g=9.8; g="gravitationalacceleration"; UnlikesomeotherlanguagessuchasCandC++,asinglekeywordservestodeclareall variables,regardlessoftheirdatatype.Intheaboveexample,thevarstatementasksthe JavaScriptinterpretertosetasidespaceforavariablenamedg.Atthetimeofthedeclaration,itisnotyetclearwhatkindofinformationtheidentiiergisgoingtorepresent.
4.4
Data and Objects
79
JavaScriptisaweaklytypedlanguage,whichmeansthattheprogrammerhasagreat deal of latitude in associating an identiier with data of a particular type. Consider the second and third lines in the above code fragment. The second line associates g with the numerical value 9.8. The third associates g with the string "gravitational acceleration"andreplacesthepreviousvaluewiththenewone.Thesestatements implythatthe“container”associatedwiththeidentiiergcanholdanythingyouwantitto holdandthatyoucanchangeyourmindaboutthenatureaswellasthevalueoftheinformation held in the container. The data declaration statement in JavaScript reserves the nameofanidentiierassociatedwithadatacontainer,butnotthenatureofitscontents.To putitanotherway,JavaScriptinfersdatatypefromthecurrentcontentsofavariablecontainer.Ifthenatureofthecontentsofthecontainer(notjustthevalue)ischanged,thenthe datatypeassociatedwiththatcontainerwillchange,too.Ifyouusespreadsheetssuchas Excel, you will be familiar with this kind of data typing. When you enter content in a spreadsheet cell, the spreadsheet imposes its own default typing for the content—as a number or text, for example. If you enter something different in the same cell, the spreadsheetreinterpretsthecontentsaccordingly. Becauseofweaktyping,itisalmostalwayspossibletoomitthevarkeywordwhen usingavariablenamefortheirsttime.Thestatement pi=3.14159; withoutapreviousvarpi;isanimplicitdatadeclarationforthevariableidentiierpi. Although this is generally allowed in JavaScript, there are a few situations where an explicitdatadeclarationisactuallyrequired.Evenwhentheyareallowed,implieddeclarationsarepoorprogrammingpracticeinanylanguageandshouldbeavoidedinyourcode. So,toavoidpotentialproblems,itisbesttobediligentaboutexplicitlydeclaringallvariables,usingthevarkeyword,beforeyouusethem.
4.4.2 Data Types JavaScript supports three basic data types (primitives): numbers, strings, and Boolean values.JavaScriptdoesnotdistinguishbetweenintegersandrealnumbers.Thatis,itdoes notprovideseparatedatatypesforintegersandrealnumbers.Instead,JavaScriptstoresall numbersinaloatingpointformat,whichprovideswhatis,ingeneral,anapproximation oftheactualvalue.Incontrast,integers,inlanguagesthatsupportaseparatedatatype, are stored as exact values, in a binary format. This distinction can have signiicant consequencesinsomekindsofnumericalcalculations. Somelanguages,suchasC/C++,haveaseparatedatatypeforrepresentingindividual characters,fromwhichstringrepresentationsarebuilt.JavaScriptworksessentiallytheother wayaround,withasinglecharacterbeingrepresentedasastringvariableoflengthone. Boolean data have one of two values, true or false. Boolean variables can be assignedoneofthesetwovalues: varx=true,y=false;
80
4
4
Fundamentals of the JavaScript Language
Notethatthewordstrueandfalsearevalues,not“names”(orstringliterals,asdeined inthenextsection),sotheyarenotenclosedinquotemarks.
4.4.3 Literals Literalsareactualnumbers,characterstrings,orBooleanvaluesembeddedincode.Inthe statement var pi=3.14159;, 3.14159 is a number literal. In the statement var name="David";,"David"isastringliteral.Theadvantageofusingliteralsisthat theirvalueisself-evident. Ingeneral,itisgoodprogrammingstyletolimittheuseofthesameliteralvaluein manyplacesinyourcode.Forexample,ratherthanusingtheliteral3.14159whenever you need the value of p, you should assign a value to the quantity p by using a data declarationstatementvarpi=3.14159;.Nowyoucaninsertthevalueofpanywhere inyourprogramjustbyreferringtoitsidentiier.SupposeyoudeclarevarB=5.195; andusethisvariablenameinseveralplacesinyourcode.If,lateron,youdecideyouneed to change the value of B to 5.196, you can make this change just once, in the data declarationstatement,andthechangewillautomaticallyapplyeverywheretheBidentiier isused.
4.4.4 Case Sensitivity JavaScriptiscasesensitive.This means that all reserved words and identiiers mustbe spelledexactlyastheyhavebeendeined.Forexample,Varisnotthesameasvar;the statement Var pi=3.14159; will generate a syntax error. If you deine a variable namedradius,youcannotlaterchangethatspellingtoRadiusorRADIUS.Because ofcasesensitivity,youcoulddeinethreeseparateidentiiersasradius,Radius,and RADIUS.However,thisispotentiallyconfusingandshouldbeavoided. Therearetworeasonswhyitisespeciallyimportanttobeverycarefulwhenyouspell namesinJavaScript.First,recallthatJavaScriptdoesn’trequireanexplicitdatadeclarationstatementforvariableidentiiers.So,youcouldwritethedeclarationstatementvar taxes,income,rate;andthen,laterinyourscript,typetexas=income*rate;. This misspelling of taxes as texas would be an obvious mistake on your part, but JavaScriptwillnotseeanythingwrongwithwhatyouhavedone. Second,rememberthatHTMLisnotcasesensitive.SinceyouwillbeusingHTMLand JavaScripttogetherinthesamedocument,itiseasytoforgetthisdistinctionbetweenthe twolanguages.Becareful!
4.4
Data and Objects
81
4.4.5 Objects and Methods for Input and Output Inplainlanguageusage,anobjectisathing—anykindofthing.Anobjecthasproperties. Perhapsitisaball—round,6cmindiameter,shiny,andred.Objectscandothings.Aball canrollandbounce.Intheworldofprogramming,objectsalsohavepropertiesandthey candothings.Forexample,thereisaMathobjectinJavaScriptthatknowsaboutmathematicalconstants(properties)andhowtodocertainkindsofmathematicalcalculations. (SeeSect.4.6below.)Inprogrammingterminology,implementationsofactionsassociated withanobjectarecalledmethods.Forexample,youmightdeineamethodtodescribe howhighaballwillbouncewhenyoudropitontoahardsurface. ThereasonobjectsareintroducednowisthatinordertoseehowJavaScriptworks,you need to display the results of calculations done in response to user input. For now, the document.write()methodofthedocumentobject,irstintroducedinChap.1,or window.alert(),amethodofthewindowobjectwillbeusedtodisplayoutput.Itis notnecessarytoincludethewindowobjectname,soitisOKsimplytowritealert(). The purpose of using these methods is to avoid, for now, worrying about the interface betweenJavaScriptandinputieldsinHTMLforms.Inlaterchapters,thesemethods willbeusedmuchlessfrequently. For the same reason,to avoid interactions withan HTMLdocument, the window. prompt(),orprompt()methodwillbeusedforinput.Bothprompt()andalert() will be used much less frequently after JavaScript and HTML forms are integrated, althoughtheywillremainusefulformonitoringtheperformanceofscripts. Suppose you wish to ask the user of a script to provide the radius of a circle. The statement varradius=prompt("Givetheradiusofacircle:"); resultsinamessageboxbeingopened ontheuser’smonitor.The“undeined” messagethatmayappearintheinput box means that the variable named radius does not currently have a value assignedto it. When avalueis typedintheinputbox,thatvaluewill be assigned to the variable radius. Then,additionallinesofcodecanbewrittentousethatvalue.Subsequentsectionsofthis chapter make frequent use of the prompt() method to get user input for a script. Document4.1showshowtousetheprompt()andalert()methods. Document4.1(circle.htm)
Calculateareaofacircle.
Suppose you type 3.3 in the input box. The following alert message box will then appearonyourscreen.
Theformatsoftheprompt()andalert()windowsarebrowser-dependentandcan’t bechangedfromwithinyourscript.1 NotetheshadedlineinDocument4.1: radius=parseFloat(radius); The purpose of parseFloat(), which is a “global” method not associated with a p articularobject,istoconvertappropriatestringsofcharactersintoanumericalrepresentation.(GlobalmethodswillbediscussedagaininChap.6.)Indocument4.1,thevariable radiusisreplacedbytheoutputfromtheparseFloat()function.Why?Because anythingenteredintheprompt()inputwindowisconsideredtobeastringofcharacters,regardlessofwhetherthosecharacters“look”likeanumber.Often,codewillwork properly without the parseFloat() method, because JavaScript will automatically applyanappropriatetypeconversion(typicallyfromastringofcharacterstoanumber). Buttherearesomepotentialproblemswithrelyingonimplicittypeconversions,aswillbe discussed in later examples. For now, sufice it to say that you should always apply parseFloat()tonumericaldataenteredthroughaprompt()regardlessofwhether itappearstobenecessary.2 Author’snote:Someofmystudentscomplainthatthealertboxlookstoomuchlikea“warning,” ratherthananinformationwindow.Fortheexamplesinthischapter,youcanusedocument. write()insteadofalert()ifthatisyourpreference. 2 Insomecases,theparseInt()method,discussedinChap.6,mightbethepreferredchoiceif thenumberistobetreatedasaninteger. 1
4.4
Data and Objects
83
4.4.6 String Methods BecauseoftheimportanceofmanipulatingstringsininteractionswithHTMLdocuments, JavaScript treats strings as objects and supports a long list of string-related methods. Table4.2listssomeusefulmethods.
Table 4.2 SomeusefulmethodsfortheStringobject MethodName
DescriptionandExamples
charAt(n)
Returnsastringcontainingnthcharacter.n=0returnsleftmost character. "HTML".charAt(3);returnsavalueofL. Returnsthebase-10ASCIIcodeforthenthcharacter.n=0returns codeforleftmostcharacter. vars="acid",t; t=s.charCodeAt(0);Thasvalue97. Concatenates(adds)thestringarguments.(Equivalenttousing+ operatorwithstrings.) var s="I".concat("love","HTML."); shasvalueIloveHTML. Buildsstringfrombase-10ASCIIvalues. vars=String.fromCharCode(65,66,67); shasvalueABC. Returnsindexofirstappearanceofstrings,atorafterthe optionalstartingindexn.Ifnisnotspeciied,searchstartsat index0.Returns–1ifsisnotfound. "excel".indexOf("x");returns1. "excel".indexOf("xce",2); returns–1. Returnsindexoflastappearanceofstrings,searchingfromright toleft,atorbeforetheoptionalstartingindexn.Ifnisnot speciied,searchstartsattheendofthestring.Returns–1ifs isnotfound. "excel".lastIndexOf("e"); returns3. "excel".lastIndexOf("l",3); returns–1. Returnsanewstringcontainingasubstringofthetargetstring oflengthlen,startingatindexm.Iflenisnotspeciied,the substringcontainsallcharactersfrommtoendoftargetstring. "excel".substr(0,5);returnsexcel. "excel".substr(2);returnscel.
charCodeAt(n)
concat({twoormore stringarguments})
fromCharCode (n1[,n2,,nn]) indexOf(s[,n])
lastIndexOf (s[,n])
substr(m[,len])
(continued)
84
4
4
Fundamentals of the JavaScript Language
Table 4.2 (continued) MethodName
DescriptionandExamples
substring (m[,end])
Returnsanewstringcontainingasubstringofthetargetstring fromindexmuptobutnotincludingindexend.Ifendisnot speciied,substringcontainsallcharactersfrommtoendof targetstring. "excel".substring(1,3); returnsxc. Returnsnewstringthatconvertsallcharactersintargetstring tolowercase. varh="HTML"; h=h.toLowerCase(); replaceshwiththenewvaluehtml. Returnsanewstringthatconvertsallcharactersinthetarget stringtouppercase. vara="ascii",A; A=a.toUpperCase(); assignsavalueofASCIItoA.
toLowerCase()
toUpperCase()
The methods of the String object in JavaScript can be applied directly to string p rimitives—variablesorliterals.Therefore,thereferencetotheStringobjectnameis rarelyneeded.Thisisincontrasttootherobjects,suchasMath,whichwillbediscussed laterinthischapter. Characters in strings are always numbered from left to right, starting with 0. So, "HTML".charAt(3); returns "L" and not "M". There is only one string property: length.Thevalueissetautomaticallywheneverthecontentsofastringarechanged;the value of length cannot otherwise be set. For example, "ThisIsJavaScript". length;returnsavalueof16. Itisimportanttounderstandthatstringmethodsdonotchangethecontentsofastring simplyasaresultofinvokingthatmethod.Rather,themethodreturnsavaluethatmustbe assignedappropriately.Hence,intheexample varh="HTML"; h=h.toLowerCase(); thestringvariablehisreplacedbyanewvalue,html,throughtheassignmentstatement. Intheexample vara="ascii",A; A=a.toUpperCase(); thevalueofstringvariableaisunchanged,whiletheresultofinvokingthetoUpperCase()methodisassignedtothestringvariableA,whichnowhasavalueofASCII.
4.5 Tokens, Operators, Expressions, and Statements
85
4.5 Tokens, Operators, Expressions, and Statements 4.5.1 Tokens Asnotedpreviously,tokensarethesmallestlexicalunitsofalanguage.Onewaytothink abouttokensistoconsiderhowascriptmightbestoredincompressedform.Eachunique pieceofinformationwillberepresentedbyatoken.Forexample,variablenameidentiiers willbestoredastokens.Theconceptoftokensexplainswhymynameormy_nameare allowed variable names, but my name is not—my name will be interpreted as two separatenames(twotokens).
4.5.2 Arithmetic Operators Operatorsarealsotokens.JavaScriptoperators,showninTable4.3,includearithmetic operatorsforaddition,subtraction,multiplication,division,andthemodulusoperatorfor returningtheremainderfromdivision.Theseareallbinaryoperators,whichmeansthat theyrequiretwooperands,onetotheleftoftheoperatorandonetotheright.Theaddition andsubtractionoperatorscanalsofunctionasunaryoperators,withasingleoperandtothe rightoftheoperator;forexample,-x. Withtheexceptionofthemodulus,orremainder,operator,theseshouldallbefamiliar. Themodulusoperatorworkswitheitherintegerorrealnumberoperands.(Rememberthat JavaScriptdoesnotsupportaseparateintegerdatatype.)Theresultofdividing17by3is 5witharemainderof2.Theresultofdividing16.6by2.7is6(6times2.7=16.2)witha remainderof16.6−16.2=0.4. Theadditionoperatoralsoworksasaconcatenationoperatorforstrings.Theexpression varauthor="David"+""+"Brooks";makesperfectsensetoJavaScript andwillgivevariableauthortheexpectedvalueof"DavidBrooks".Notethatthe expression"David"+"Brooks"willproducetheresult"DavidBrooks." WhenJavaScriptinterpretsanexpression,itscanstheexpressionfromlefttorightone ormoretimes.Operationsimpliedbythepresenceofoperatorsareevaluatedaccordingto precedencerules.Fortunately,theserulesarethesameonesthatapplyinalgebraicexpressions.Supposea=3,b=4,andc=5.Whatisthevalueofxinthealgebraicexpression x = a + bc ?Basedonprecedencerules,multiplicationanddivisionoperationsarecarried outbeforeadditionandsubtraction.So, x = 3 + 4·5 = 3 + 20 = 23 .Thatis,amultiplication operationhasprecedenceoveranadditionoperation,sotheadditionoperationisdelayed untilafterthemultiplicationisperformed,eventhoughtheadditionoperatoristotheleft of the multiplication operator. Parentheses are required to alter the precedence rules: x = (3 + 4 ) ·5 = 35 .
86
4
4
Fundamentals of the JavaScript Language
Table 4.3 JavaScript’sarithmeticoperators Operator
Symbol
Examples
Precedence
Addition Subtraction Multiplication Division Modulus(remainder)
+ − * / %
3+4 Z−10 A*b z/3.333 17%3(=2), 16.6%2.7(=0.4)
2 2 1 1 1
The same rules apply in JavaScript. As indicated in Table 4.3, multiplication and d ivision(includingthemodulusoperation)takeprecedenceoveradditionandsubtraction. So,inthiscode: vara=3,b=4,c=5; varx,y; x=a+b*c; y=(a+b)*c; thevariablexhasavalueof23.Inthefourthstatement,parenthesesareusedtooverride thenaturalorderinwhichoperationsareevaluated,soyhasavalueof35.Theexpression is evaluated from the innermost set of parentheses outward, so the a+b operation is performedbeforethemultiplicationbyc.
4.5.3 The Assignment Operator The JavaScript assignment operator is the symbol =. Thus, the JavaScript statement x=a+b;looksverymuchlikethealgebraicequation x = a + b.However,theyarenotat allthesamething!Inprogramming,theassignmentoperatorhasacompletelydifferent meaningfromthesymbolicequalityimpliedbythealgebraicuseofthe=sign.Inalgebra, the equation x = a + b deines a symbolic relationship among a, b, and x; whatever the valuesofx,a,andb,xmustbeequaltothesumofaandb.Givenvaluesforaandb,you candeterminethevalueofx.Giventhevaluesofxanda,youcansolveforthevalueofb: b = x − a .Notealsothat a + b = x isalgebraicallyequivalentto x = a + b. But,inprogramming, Themeaningoftheassignmentoperatoris:“Evaluatetheexpressionontheright sideoftheassignmentoperatorandassigntheresulttotheidentiierontheleft sideoftheassignmentoperator.” Forthestatementx=a+b;,thespeciicmeaningis“Ifaandbhavebeengivennumerical values,calculatetheirsumandassigntheresulttotheidentiierx.Ifaand/orbarestrings, concatenatebtoa.”
4.5 Tokens, Operators, Expressions, and Statements
87
Withthisdeinitionoftheassignmentoperator,itisclearthattheJavaScriptstatement a+b=x;makesnosense,andwillgenerateasyntaxerror.Why?Because: Onlyanidentiiercanappearontheleftsideoftheassignmentoperator. Finally,notethatthealgebraicexpression x = x + 1 makesnosenseatallbecauseitis notpossibleforxtobeequalitselfplus1.However,theJavaScriptstatementx=x+1; makesperfectsense.Itmeans“Add1tothecurrentvalueofxandthenreplacethevalue ofxwiththisnewvalue.”So,asaresultofexecutingthesestatements: varx=5.5; x=x+1; xwillhaveavalueof6.5. Itissometimesdificultforbeginningprogrammerstorememberthatanassignment statementisnotthesamethingasanalgebraicequation.AlthoughJavaScript(andother programming languages) allow you to perform mathematical operations with variable identiiers, these languages do not understand the concepts of algebra. When it sees an assignmentoperator,allitknowshowtodoisevaluatetheexpressionontherightsideof theoperatorandassignthatresulttotheidentiierontheleftsideoftheexpression.In doingtheexpressionevaluation,itassumesthateveryidentiierhasalreadybeenassigned anactual,andnotjustasymbolic,value. As a result of how the assignment operator works, a general rule about assignment statementsis: An identiier should never appear on the right side of an assignment operator unlessithaspreviouslybeenassignedanappropriatevalue. Identiiersthatdonotfollowthisrulearecalleduninitializedvariables.Theyareoften assigned a value of 0 by default, but you should never violate the rule based on this assumption.
4.5.4 Shorthand Arithmetic/Assignment Operators Table 4.4 shows some shorthand operators for combining arithmetic operations and a ssignments.Theyarepopularamongprogrammersbecausetheyareeasytowritequickly, buttheiruseisneveractuallyrequired. Theincrementoperator(++)adds1tothevalueofthevariabletowhichitisapplied, and the decrement operator (--) subtracts 1. These operators are commonly used in loopingstructures,asdiscussedlaterinthischapter. AsshowninTable4.4,youcanapplytheincrementordecrementoperatorseither beforethevariablename(pre-incrementorpre-decrement)orafter(post-increment or post-decrement). This choice can lead to some unexpected results. Consider Document4.2.
88
4
4
Fundamentals of the JavaScript Language
Table 4.4 Shorthandarithmetic/assignmentoperators Operator
Implementation
Interpretation
+= -= *= /= %= ++ --
x+=y; x-=y; x*=y; x/=y; x%=y; x++;or++x; y--;or--y;
x=x+y; x=x-y; x=x*y; x=x/y; x=x%y; x=x+1; x=x-1;
Document4.2(incrementDecrement.htm)
Increment/decrementoperators
In the post-increment case, the value of x is incremented after the expression is evaluated to provideavaluefory.Inthepre-incrementcase,thevalueofxisincrementedbeforethevalue ofyiscalculated.Asimilarresultwouldoccurforthedecrementoperator.Forthemost part, you should avoid combining the increment/decrement operators with other operationsinasingleexpression.Also,donotapplybothpre-andpost-operatorsatthesame time(thatis,donotwrite++x++;or--x--;)anddonotapplytheseoperatorstothe samevariablemorethanonceinanexpression.
4.6 The JavaScript Math Object
89
4.6 The JavaScript Math Object Inorderforaprogramminglanguagetobeusefulforscientiicandengineeringcalculations, itneedsnotonlybasicarithmeticoperators,butalsotheabilitytocarryoutothermathematicaloperations,suchasyouwouldindonascientiiccalculator.InJavaScript,these operationsarepackagedasmethodsintheMathobject.TheMathobjectalsohasproperties that provide some useful mathematical values, such as p. The methods implement mathematical functions, such as trigonometric functions. The methods (with a single exceptionasnotedbelow)haveoneortworeal-numberargumentsandalwaysreturna real-number result, even when that result is a whole number that looks like an integer. SomemethodsandpropertiesoftheMathobjectaresummarizedinTable4.5. Table 4.5 SomepropertiesandmethodsoftheJavaScriptMathobject Property
Description
Math.E Math.LN2 Math.LN10 Math.LOG2E Math.LOG10E Math.PI Math.SQRT1_2 Math.SQRT2
Baseofthenaturallogarithm,e,2.71828 Naturallogarithmof2,0.693147 Naturallogarithmof10,2.302585 Logtothebase2ofe,1.442695 Logtothebase10ofe,0.434294 p,3.1415927 Squarerootof½,0.7071067 Squarerootof2,1.4142136
Method
Returns
Math.abs(x) Math.acos(x) Math.asin(x) Math.atan(x)
Absolutevalueofx Arccosineofx,±p,for−1£x£1 Arcsineofx,±p/2,for−1£x£1 Arctangentofx,±p/2,for−∞ >=
³ £ =
2 2 2 2 3
-3.317.5 7.7>=7.7 7.6(mbar)
TheHTMLcodeinDocument4.11providesdefaultvaluesfortheinputields.The outputreproducedhereisforthesedefaultvalues. Earlier discussions noted that JavaScript script was often, but not always, contained withinascriptelementintheheadofadocument.But,Document4.11showsthat JavaScript statements can appear in a document without a script element. It is not
106
4
4
Fundamentals of the JavaScript Language
obviousthatthisshouldbeso—youcouldeasilyimagineascenarioinwhichJavaScript statementswereallowedtoexistonlyinsideascriptelement. The"button"ieldallowsausertoinitiateanactionbyclickinganywhereonthe button.Inthiscase,aclickinitiatesthecalculationofstationpressurebasedonthevalues currently in the elevation and sea_level_pressure ields—either the default valuesornewvaluesenteredbytheuser.Inordertorespondtoamovingamousecursor overthebuttonieldandclicking,HTMLusesaneventhandler,animportantmeansof providinginteractionbetweenadocumentanditsuser.Eventhandlersareattributes(of input) whose “values” consist of a set of JavaScript instructions enclosed in quotes. Thereareseveraleventhandlers,butinthischapteronlyonclickwillbeused.(Wewill returntothetopicofeventhandlersinChap.6.)InDocument4.11,theeventtobe“handled”isaclickofamousewhenitscursorissomewhereinthescreenspacedeinedbythe “Clickheretogetstationpressure”button. HowisinformationtransmittedfromaformieldtoJavaScript?Itwillnotworktouse, for example, just the elevation name from the form ield. Why not? Because elevationisjustthename of the ield, not its value. Form ields have attributes, suchasname,andthoseattributes have values, such as elevation. The attributes have values, too, accessed through the “dot notation” shown.OneofthevaluesofaieldnameisitsdefaultValue,whichisthevalueoriginally assignedtotheformieldintheHTMLdocument;thisvaluecanbeleftblank. Ofinteresthereisvalue,eitherthesameasdefaultValueoranewvalueentered bytheuser.Itisthevalueattributethatprovidestheinputforacalculationandwill also receive calculated results in other form ields. Applying the parseFloat (elevation.value)methodtranslatesthetextinvalueintoanumericalvalue. Using just elevation as the argument for parseFloat() makes no sense at all from JavaScript’s point of view. It may seem cumbersome to use this notation, but rememberthatthenameassignedtoanHTMLformieldissimplynotthesamethingas anidentiierinJavaScript. OnceamouseisclickedoverthebuttonieldinDocument4.11,theJavaScriptstatement is executed. The application of parseFloat() to the values in the elevation and sea_level_pressure ieldsisrequiredforthesamereasonspreviouslydiscussed fornumericalvaluesenteredthroughprompt().ThedistinctionbetweentextandnumericalvaluesiseasytoforgetbecauseJavaScriptoftenappliestypeconversionstotextvalues, onitsown.InDocument4.11,thecalculationfortheresultieldcouldalsobewrittenas result.value=sea_level_pressure.value– elevation.value/9.2;//Badidea! However,ifyoureplacethe“-”signwitha“+”sign,thenumericalcalculationwillnotbe done!(Tryitandsee.)Whatisthedifference?The“+”operatorhasaspeciicmeaningwhen appliedtostrings(itisinterpretedasaconcatenationoperator),butthe“-”operatordoesnot.
4.10
More Examples
107
Whenitencountersasubtractionoperator,JavaScriptis“smartenough”tounderstandthat thetextvaluesmustbeconvertedtonumbersinordertocarryoutthespeciiedactionbut, fromJavaScript’spointofview,thisisnotnecessaryforthe“addition”operator. Typeconversionissuesalsoapplywhenresultsofanumericaloperationareassignedto aformieldname.Althoughresult.value=…lookslikeanassignmentofonenumericalvaluetoanother,thenumericalresultmustactuallybeconvertedbacktotextbeforeit can be assigned to result.value. You might think that some kind of “convert this numbertotext”methodisrequired,andinsomesenseitis,butyoudon’thavetospecify thisconversioninyourscriptbecauseJavaScriptautomaticallydoesitforyou. Finally,clickinganywhereonthe“Resetallields”buttonsetsallinputsbacktotheir originalvalues.JavaScriptdoesthisbyaccessingthedefaultValueassignedtoeach ield.
4.10 More Examples 4.10.1 Solving the Quadratic Equation Hereisasimplealgebraiccalculationthatiseasytoimplement. Forthequadraticequation ax 2 + bx + c = 0 ,indtherealroots:
(
r1 = −b + b2 − 4ac
)
1/ 2
(
2a r = −b − b2 − 4ac 2
)
1/ 2
2a
The“a”coeficientmustnotbe0.Ifthediscriminant b 2 − 4ac = 0 ,thereisonlyone root.Ifb2−4acislessthan0,therearenorealroots. Document4.12(quadratic.htm)
SolvingtheQuadraticEquation
Entercoeficientsforax2+bx+c=0:
a= (mustnotbe0) b= c= clickforr1= clickforr2=
Thisisaworkablesolutiontotheproblem,butitis certainly not elegant or thorough. (It’s the kind of applicationyoumightwrite for your own use, but you mightnotwanttodistribute itgloballyontheWeb!)For example, no check is performed on the discriminant to see if it’s non-negative beforetheMath.sqrt()methodisapplied.However,ifthediscriminantisnegative, thenJavaScriptwillsimplyassignavalueofNaNtotheresult,whichcanbeinterpretedas amessagethattherearenorealroots. NotetheuseinDocument4.12ofthe…tagtodisplayexponentsand othersuperscriptsinHTML.The…tagwilldisplaysubscripts.
4.10.2 Rectangular Rule Numerical Integration Programming languages such as JavaScript do not “know” about symbolic mathematics, including calculus, so they can’t be used to perform analytic integration of functions. However,thereareseveralwaystointegratefunctionsnumerically.Thisisespeciallyuseful forfunctionsthatdonothaveanalyticintegrals,suchasthenormalprobabilitydensityfunction(seeExercise6.6).RectangularRuleintegrationisthesimplestofthesemethods. Assumef(x)=x2.Tocalculateanapproximationtotheintegraloff(x),specifythelower andupperboundariesfortheintegration,x0andx1.Dividetheinterval(x1−x0)inton equalintervals,dx=(x1−x0)/n.Then, INITIALIZEintegral=0(Initializethevalueto0.) LOOPfori=0ton−1, x = x0 + i • dx + dx / 2 y=x•x(Thiscouldbeanyfunctionofx.) integral=integral+y END LOOP ASSIGNintegral=integral•dx
4.10
More Examples
109
ThegraphillustratestheRectangularRuleintegrationoff(x)=x2overtheinterval1–4, withn=3.Thesumoftheareasofthegrayrectanglesistheapproximationtotheintegral. Forimplementationincode,nshouldbemuchlargerthan3! 16
f(x) = x2
12
8
4
0 0.0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
x
Document4.13(RectangularRule.htm)
RectangularRuleintegration forf(x)=x2
x0:
x1:
Theanalyticintegraloff(x)=x2isx3/3.Thevalueoftheintegralovertheinterval1–4 is 43/3−13/3=(64−1)/3=21. Document 4.13 gives a value that is close but not exact. Increasingnwillimprovetheapproximation.Ingeneral,numericalintegrationalgorithms workwellfor“wellbehaved”functionsbuttheywillnotgiveexactvalues. Itispossibletowritecodethatallowsausertoenterafunctioninanield, expressedinproperJavaScriptsyntax,ratherthanhavingto“hardcode”thefunctionasin thisexample.(SeeExercise6.6.)
Using Arrays in HTML/JavaScript
5
Abstract Chapter5presentsanintroductiontoarrays.Itexplainshowtodeinearraysin JavaScript,howtousethem,andhowtousearraystointeractwithanHTMLform.
5.1 Basic Array Properties Theconceptofarraysisextremelyimportantinprogramming,asitprovidesawayto organize,access,andmanipulaterelatedquantities.Itisimportanttoformamentalmodel ofhowarraysareimplemented,asshowninthesketch.Itmaybehelpfultothinkofapost oficeanalogy.Thepostoficehasaname,equivalenttothenameofanarray.Insidethe post ofice are numbered mail boxes. The numbers on the boxes correspond to array “addresses,”calledindices.Thecontentsoftheboxescorrespondtoarrayelements.In many programming languages, including JavaScript, the numbering of array elements alwaysbeginsat0ratherthan1.
JavaScript supports an Array object for creating, using, and manipulating related v alues.ThemostimportantArraymethodistheconstructornew Array(),which allowsyoutocreatearrays.Syntaxpossibilitiesfordoingthisinclude: varArray1=newArray(); varArray2=newArray(value_1,value_2,…,value_n); varArray3=newArray(10);
D.R.Brooks,GuidetoHTML,JavaScriptandPHP:ForScientistsandEngineers, DOI10.1007/978-0-85729-449-4_5,©Springer-VerlagLondonLimited2011
111
112
5
5
Using Arrays in HTML/JavaScript
TheirststatementcreatesanemptyarraynamedArray1.Thesecondstatementcreates anarrayofnelementswithinitialvaluesasprovidedbythearguments.Thethirdstatementcreatesanarraywithtenelementswhosevaluesareunspeciied.Because,aswillbe shown later, the declared size of an array is easily overridden, it makes little sense to declareanarrayusingthesyntaxofthethirdstatement. It is not actually necessary to invoke the Array() constructor in order to create a JavaScriptarray.Eachofthesestatementswillcreateanarray: varArray1=[]; varArray2=[value_1,value_2,…,value_n]; varArray3=[,,,,,,,,,]; Notetheuseofsquarebracketnotationratherthanparenthesesinthissyntax.Thethird statement,withninecommas,impliesanemptyarrayoftenelements.Thissyntaxmight beusefulfordeclaringsparse(mostlyempty)arrays: varSparseArray=[1.1,,3.3,,,,]; Array elements can also be assigned by using variable names that already have appropriatevalues.Thestatements vara=3.3,b=5.5,c=7.7; varA=[a,b,c]; createarrayAwiththreeelementsequalto3.3,5.5,and7.7. Squarebracketnotationisalsousedtoaccesstheelementsofanarray.Individualarray elementscanappeartoeithertherightortheleftofanassignmentoperator,withtheusual provisionthatarrayelementsappearingontherightsideofanassignmentoperatorshould alreadyhavebeengivenanappropriatevalue.Thatis,youcanuseassignmentstatements toassignvaluestoundeinedarrayelementsortochangepreviouslyassignedvalues: vara=3.3,b=5.5,c=7.7; varA=[a,b,c]; varx,y=17.9,z=13.3; x=A[0]+A[1]+A[2]; A[2]=y+z; Arrayindicescanbenumbers,asintheaboveexample,oridentiiers,suchasx[i],or evenexpressions,suchasx[2*j+3],assumingtheidentiierorexpressionrepresentsan integervalue.If,forexample,j=2.5,theindexis(2)(2.5)+3=8,andthisisanallowed index,assumingthereareatleastnineelementsinx.However,ifj=2.3,x[2*j+3]is undeined because (2)(2.3)+3 is not a whole number. For the same reason, x[1] is deined,butx[4/3]isnot. Unlikesomeotherlanguages,JavaScriptallowsanarraydeclarationtobeoverridden later in the script. Continuing with the above example, it is easy to add one or more additionalelements:
5.1
Basic Array Properties
113
A[3]=A[0]+A[1]; A[4]=15.6; Bearinginmindthatarraysareobjects,thecurrentlengthofanarrayiscontainedinthe length property. For the above example, A.length has a value of 5. The value of lengthisequaltothenumberofdeclaredlocationsinthearray.Tolookatitanother way,lengthgivesthevalueofthenextavailablearrayindex.Thisistrueregardlessof whether any or all of the array elements have been assigned values. For example, the statements varA=newArray(5); alert(A.length); displayavalueof5despitethefactthatthearrayAisempty. AusefulfeatureofJavaScriptarraysisthatnotallelementsmustcontainthesamekind ofdata.Document5.1givesasimpleexampleinwhicharrayelementsareamixtureof numbersandtextstrings. Document5.1(siteData.htm)
SiteNames
Document5.1showshowthelengthpropertyofanarrayisusedtodeterminethe terminatingconditioninafor…looptoaccessalltheelementsofthearray.Remember thattheindexvalueofthelastelementinanarrayisalwaysonelessthanthetotalnumber of elements in the array. This is why the terminating condition is i
336
12 Using Graphics with PHP
12
Theinalstep,asinpreviousapplications,istoplacethelinegraphcodeinsideafunctionanduseanHTMLinterfacetoprovideinputvaluestoPHPcodethatcallsthefunction. Documents12.9a,bgivetheHTMLandPHPcodeforthisapplication.Thiscodeshould beconsideredjustasanexampleofhowtographvaluesextractedfromadataile,rather thanasageneral-purposeinterface,becausethedrawingofanylinegraphwilldepend considerablyonthenatureofthedatabeingplottedandtheformatinwhichitisstored.It iscertainlynotpossibletospecifyorplanforinadvanceallthepossibleformatsthatwill determinethecodeneededtoreadandprocessthedata. Document12.8bwasusedtodisplaytheirst8daysofsolardata,sampledatone-minute intervals,andstoredinailewhosenameishard-codedintothedocument.Itwasnecessarytoknowthestructureofthisileinordertoprocessthedata.TheHTMLinterface showninDocument12.9asimplyspeciiesthenameofailethatcontainsonlypairsof X–Y values to be graphed; this represents thesimplestpossible case ofprocessingdata fromanexternalile. Document12.9a(lineGraphTest.htm)
LineGraph
Drawalinegraph
Charttitle: X-axistitle: Y-axistitle: Xmin: Xmax: Ymin: Ymax: X-axislabels: Y-axislabels: X-titleoffset(pixels): Y-titleoffset(pixels): NameofilecontainingX-Yvalues:
338
12
12
Using Graphics with PHP
Document12.9b(lineGraph.php)
Theinputileusedtotestthisapplication,June2008data.txt,containsone-minute datasampledinsolationfortheentiremonthofJune—43,200X–Ypairs.Thesevaluesare readintotwoarraysinthemainprogramsectionofDocument12.9bandpassedtothe lineGraph()function,ratherthanpassingtheilenametothefunctionandreadingand graphingthevaluesoneX–Ypairatatimewithinthefunction.Thelatterchoiceisperfectlyacceptable,butthechoiceimplementedinDocument12.9bshowsthatPHPiscapableofhandlingverylargearrays. Here is a much smaller data ile that can easily be copied and tried with this application: 0.582 0.681 0.746 0.799 0.849 0.896 0.931 0.962 1.006 1.037 1.068
0.003 0.003 0.003 0.003 0.003 0.003 0.003 0.003 0.003 0.003 0.003
8.2398 7.0438 6.2972 5.6974 5.1569 4.7228 4.4054 4.1332 3.7906 3.5338 3.2936
342
12
1.091 1.121 1.158 1.176 1.203 1.223 1.24 1.25 1.272
12
0.003 0.003 0.003 0.003 0.003 0.003 0.003 0.003 0.003
Using Graphics with PHP
3.0758 2.8257 2.6090 2.4870 2.3003 2.1956 2.1043 1.9784 1.8467
The irst and second columns are voltage outputs V and Vo from a sun-viewing i nstrumentcalledasunphotometer.Thethirdcolumnisthe“relativeairmass”m—a measure of the amount of atmosphere between the instrument, starting early in the morning.Forthissetofmeasurements,thequantityln(V−Vo)plottedagainstmshould beastraightline. Asisoftenthecasewiththeseapplications,somemodiicationsneedtobemadeinthe main program to prepare the arrays for graphing. These are shown in the shaded code below.Inthemainprogram,thelogarithmoftheirstcolumnminusthesecondiscalculated andplacedintheYarray.Inthegraphingfunction,codeisaddedtomarkeachdatapoint withailledcircle. $x1=($X[0]-$xmin)/($xmax-$xmin)*$xaxis_length; $y1=($Y[0]-$ymin)/($ymax-$ymin)*$yaxis_length; ImageFilledEllipse($im,$x0+$x1,$y0-$y1,10,10,$data_color); for($i=1;$i
… &inin; ∫ &iques; “ ‘ ≤