Académique Documents
Professionnel Documents
Culture Documents
JavaScriptwasdesignedtoaddinteractivitytoHTMLpages
JavaScriptisascriptinglanguage
Ascriptinglanguageisalightweightprogramminglanguage
JavaScriptisusuallyembeddeddirectlyintoHTMLpages
JavaScriptisaninterpretedlanguage(meansthatscriptsexecutewithoutpreliminarycompilation)
WhatcanaJavaScriptdo?
JavaScriptcanputdynamictextintoanHTMLpage
JavaScriptcanreacttoeventsAJavaScriptcanbesettoexecutewhensomethinghappens,likewhena
pagehasfinishedloadingorwhenauserclicksonanHTMLelement
JavaScriptcanreadandwriteHTMLelementsAJavaScriptcanreadandchangethecontentofan
HTMLelement
JavaScriptcanbeusedtovalidatedataAJavaScriptcanbeusedtovalidateformdatabeforeitis
submittedtoaserver.Thissavestheserverfromextraprocessing
JavaScriptcanbeusedtocreatecookiesAJavaScriptcanbeusedtostoreandretrieveinformationon
thevisitor'scomputer
TheRealNameisECMAScript.JavaScriptisanimplementationoftheECMAScriptlanguage
standard.ECMAScriptisdevelopedandmaintainedbytheECMAorganization.ECMA262istheofficial
JavaScriptstandard.ThelanguagewasinventedbyBrendanEichatNetscape(withNavigator2.0),andhas
appearedinallNetscapeandMicrosoftbrowserssince1996.ThedevelopmentofECMA262startedin1996,and
thefirsteditionofwasadoptedbytheECMAGeneralAssemblyinJune1997.Thestandardwasapprovedasan
internationalISO(ISO/IEC16262)standardin1998.Thedevelopmentofthestandardisstillinprogress.
StructureofJavaScript
<html>
<head>
<scripttype="text/javascript">
document.writeln(HeloWorld!)
</script>
</head>
<body>
</body>
</html>
ToinsertaJavaScriptintoanHTMLpage,weusethe<script>tag.Insidethe<script>tagweusethetypeattribute
todefinethescriptinglanguage.
So,the<scripttype="text/javascript">and</script>tellswheretheJavaScriptstartsandends.Itispossibletohave
scriptcodeinsidethebodytagalsoasshownbelow.Ifitisplacedinsidethebodytag,thescriptwillbeexecuted
whenthecontentofHTMLdocumentisdisplayed.
<html>
<body>
<scripttype="text/javascript">
............
</script>
</body>
</html>
Thedocument.writecommandisastandardJavaScriptcommandforwritingoutputtoapage.Byenteringthe
document.writecommandbetweenthe<script>and</script>tags,thebrowserwillrecognizeitasaJavaScript
commandandexecutethecodeline.InthiscasethebrowserwillwriteHelloWorld!tothepage:
Scriptsin<head>
Scriptstobeexecutedwhentheyarecalled,orwhenaneventistriggered,areplacedinfunctions.Itisagood
practicetoputallyourfunctionsintheheadsection,thiswaytheyareallinoneplaceanddonotinterferewithpage
content.
Example
<html>
<head>
<scripttype="text/javascript">
functionmessage()
{
alert("Thisalertboxwascalledwiththeonloadevent")
}
</script>
</head>
<bodyonload="message()">
</body>
</html>
JavaScriptsinapagewillbeexecutedimmediatelywhilethepageloadsintothebrowser.Thisisnotalwayswhat
wewant.Sometimeswewanttoexecuteascriptwhenapageloads,oratalaterevent,suchaswhenauserclicksa
button.Whenthisisthecaseweputthescriptinsideafunction
Scriptsin<head>and<body>
Youcanplaceanunlimitednumberofscriptsinyourdocument,andyoucanhavescriptsinboththebodyandthe
headsectionatthesametime.
Example
<html>
<head>
<scripttype="text/javascript">
functionmessage()
{
alert("Thisalertboxwascalledwiththeonloadevent")
}
</script>
</head>
<bodyonload="message()">
<scripttype="text/javascript">
document.write("ThismessageiswrittenbyJavaScript")
</script>
</body>
</html>
UsinganExternalJavaScript
JavaScriptcanalsobeplacedinexternalfiles.ExternalJavaScriptfilesoftencontainscodetobeusedonseveral
differentwebpages.ExternalJavaScriptfileshavethefileextension.js.Externalscriptcannotcontainthe
<script></script>tags.Touseanexternalscript,pointtothe.jsfileinthe"src"attributeofthe<script>tag:
Example
<html>
<head>
<scripttype="text/javascript"src="xxx.js"></script>
</head>
<body>
</body>
</html>
JavaScriptVariables
JavaScriptvariablesareusedtoholdvaluesorexpressions.Avariablecanhaveashortname,likex,oramore
descriptivename,likecarname.RulesforJavaScriptvariablenames:
Variablenamesarecasesensitive(yandYaretwodifferentvariables)
Variablenamesmustbeginwithaletterortheunderscorecharacter
BecauseJavaScriptiscasesensitive,variablenamesarecasesensitive.
Declaring(Creating)JavaScriptVariables
CreatingvariablesinJavaScriptismostoftenreferredtoas"declaring"variables.YoucandeclareJavaScript
variableswiththevarkeyword:
varx
varcarname
Afterthedeclarationshownabove,thevariablesareempty(theyhavenovaluesyet).However,youcanalsoassign
valuestothevariableswhenyoudeclarethem:
varx=5
varcarname="Volvo"
Aftertheexecutionofthestatementsabove,thevariablexwillholdthevalue5,andcarnamewillholdthevalue
Volvo.
AssigningValuestoUndeclaredJavaScriptVariables
Ifyouassignvaluestovariablesthathavenotyetbeendeclared,thevariableswillautomaticallybedeclared.These
statements:
x=5
carname="Volvo"
havethesameeffectas:
varx=5
varcarname="Volvo"
RedeclaringJavaScriptVariables
IfyouredeclareaJavaScriptvariable,itwillnotloseitsoriginalvalue.
varx=5
varx
Aftertheexecutionofthestatementsabove,thevariablexwillstillhavethevalueof5.Thevalueofxisnotreset
(orcleared)whenyouredeclareit.
TheLifetimeofJavaScriptVariables
Ifyoudeclareavariablewithinafunction,thevariablecanonlybeaccessedwithinthatfunction.Whenyouexitthe
function,thevariableisdestroyed.Thesevariablesarecalledlocalvariables.Youcanhavelocalvariableswiththe
samenameindifferentfunctions,becauseeachisrecognizedonlybythefunctioninwhichitisdeclared.
Ifyoudeclareavariableoutsideafunction,allthefunctionsonyourpagecanaccessit.Thelifetimeofthese
variablesstartswhentheyaredeclared,andendswhenthepageisclosed.
JavaScriptArithmeticOperators
Arithmeticoperatorsareusedtoperformarithmeticbetweenvariablesand/orvalues.Giventhaty=5,thetable
belowexplainsthearithmeticoperators:
Operator
+
*
/
%
++
Description
Addition
Subtraction
Multiplication
Division
Modulus(divisionremainder)
Increment
Decrement
Example
x=y+2
x=y2
x=y*2
x=y/2
x=y%2
x=++y
x=y
Result
x=7
x=3
x=10
x=2.5
x=1
x=6
x=4
JavaScriptAssignmentOperators
AssignmentoperatorsareusedtoassignvaluestoJavaScriptvariables.Giventhatx=10andy=5,thetablebelow
explainstheassignmentoperators:
Operator
=
+=
=
*=
/=
%=
Example
x=y
x+=y
x=y
x*=y
x/=y
x%=y
SameAs
x=x+y
x=xy
x=x*y
x=x/y
x=x%y
Result
x=5
x=15
x=5
x=50
x=2
x=0
ComparisonOperatorsComparisonoperatorsareusedinlogicalstatementstodetermineequalityordifference
betweenvariablesorvalues.Giventhatx=5,thetablebelowexplainsthecomparisonoperators:
Operator
==
===
Description
isequalto
isexactlyequalto(valueandtype)
!=
>
<
>=
<=
isnotequal
isgreaterthan
islessthan
isgreaterthanorequalto
islessthanorequalto
Example
x==8isfalse
x===5istrue
x==="5"isfalse
x!=8istrue
x>8isfalse
x<8istrue
x>=8isfalse
x<=8istrue
LogicalOperators
Logicaloperatorsareusedtodeterminethelogicbetweenvariablesorvalues.Giventhatx=6andy=3,thetable
belowexplainsthelogicaloperators:
Operator
&&
||
!
Description
and
or
not
Example
(x<10&&y>1)istrue
(x==5||y==5)isfalse
!(x==y)istrue
ConditionalOperator
JavaScriptalsocontainsaconditionaloperatorthatassignsavaluetoavariablebasedonsomecondition.
Syntax
variablename=(condition)?value1:value2
Example
greeting=(visitor=="PRES")?"DearPresident":"Dear"
ConditionalStatements
Veryoftenwhenyouwritecode,youwanttoperformdifferentactionsfordifferentdecisions.Youcanuse
conditionalstatementsinyourcodetodothis.
InJavaScriptwehavethefollowingconditionalstatements:
ifstatementusethisstatementtoexecutesomecodeonlyifaspecifiedconditionistrue
if...elsestatementusethisstatementtoexecutesomecodeiftheconditionistrueandanothercodeifthe
conditionisfalse
if...elseif....elsestatementusethisstatementtoselectoneofmanyblocksofcodetobeexecuted
switchstatementusethisstatementtoselectoneofmanyblocksofcodetobeexecuted
IfStatement
Usetheifstatementtoexecutesomecodeonlyifaspecifiedconditionistrue.
Syntax
if(condition)
{
codetobeexecutedifconditionistrue
}
Notethatifiswritteninlowercaseletters.Usinguppercaseletters(IF)willgenerateaJavaScripterror!
Example
<scripttype="text/javascript">
//Writea"Goodmorning"greetingif
//thetimeislessthan10
vard=newDate()
vartime=d.getHours()
if(time<10)
{
document.write("<b>Goodmorning</b>")
}
</script>
If...elseStatement
Usetheif....elsestatementtoexecutesomecodeifaconditionistrueandanothercodeiftheconditionisnottrue.
Syntax
if(condition)
{
codetobeexecutedifconditionistrue
}
else
{
codetobeexecutedifconditionisnottrue
}
Example
<scripttype="text/javascript">
//Ifthetimeislessthan10,youwillgeta"Goodmorning"greeting.
//Otherwiseyouwillgeta"Goodday"greeting.
vard=newDate()
vartime=d.getHours()
if(time<10)
{
document.write("Goodmorning!")
}
else
{
document.write("Goodday!")
}
</script>
If...elseif...elseStatement
Usetheif....elseif...elsestatementtoselectoneofseveralblocksofcodetobeexecuted.
Syntax
if(condition1)
{
codetobeexecutedifcondition1istrue
}
elseif(condition2)
{
codetobeexecutedifcondition2istrue
}
else
{
codetobeexecutedifcondition1andcondition2arenottrue
}
Example
scripttype="text/javascript">
vard=newDate()
vartime=d.getHours()
if(time<10)
{
document.write("<b>Goodmorning</b>")
}
elseif(time>10&&time<16)
{
document.write("<b>Goodday</b>")
}
else
{
document.write("<b>HelloWorld!</b>")
}
</script>
TheJavaScriptSwitchStatement
Usetheswitchstatementtoselectoneofmanyblocksofcodetobeexecuted.
Syntax
switch(n)
{
case1:
executecodeblock1
break
case2:
executecodeblock2
break
default:
codetobeexecutedifnisdifferentfromcase1and2
}
JavaScriptPopupBoxes
JavaScripthasthreekindofpopupboxes:Alertbox,Confirmbox,andPromptbox.
AlertBox
Analertboxisoftenusedifyouwanttomakesureinformationcomesthroughtotheuser.Whenanalertboxpops
up,theuserwillhavetoclick"OK"toproceed.
Syntax
alert("sometext")
Example
<html>
<head>
<scripttype="text/javascript">
functionshow_alert()
{
alert("Iamanalertbox!")
}
</script>
</head>
<body>
<inputtype="button"onclick="show_alert()"value="Showalertbox"/>
</body>
</html>
ConfirmBox
Aconfirmboxisoftenusedifyouwanttheusertoverifyoracceptsomething.Whenaconfirmboxpopsup,the
userwillhavetoclickeither"OK"or"Cancel"toproceed.Iftheuserclicks"OK",theboxreturnstrue.Iftheuser
clicks"Cancel",theboxreturnsfalse.
Syntax
confirm("sometext")
Example
<html>
<head>
<scripttype="text/javascript">
functionshow_confirm()
{
varr=confirm("Pressabutton")
if(r==true)
{
alert("YoupressedOK!")
}
else
{
alert("YoupressedCancel!")
}
}
</script>
</head>
<body>
<inputtype="button"onclick="show_confirm()"value="Showconfirmbox"/>
</body>
</html>
PromptBox
Apromptboxisoftenusedifyouwanttheusertoinputavaluebeforeenteringapage.Whenapromptboxpops
up,theuserwillhavetoclickeither"OK"or"Cancel"toproceedafterenteringaninputvalue.Iftheuserclicks
"OK"theboxreturnstheinputvalue.Iftheuserclicks"Cancel"theboxreturnsnull.
Syntax
prompt("sometext","defaultvalue")
Example
<html>
<head>
<scripttype="text/javascript">
functionshow_prompt()
{
varname=prompt("Pleaseenteryourname","HarryPotter")
if(name!=null&&name!="")
{
document.write("Hello"+name+"!Howareyoutoday?")
}
}
</script>
</head>
<body>
<inputtype="button"onclick="show_prompt()"value="Showpromptbox"/>
</body>
</html>
JavaScriptFunctions
Afunctionwillbeexecutedbyaneventorbyacalltothefunction.
JavaScriptFunctions
Tokeepthebrowserfromexecutingascriptwhenthepageloads,youcanputyourscriptintoafunction.Afunction
containscodethatwillbeexecutedbyaneventorbyacalltothefunction.Youmaycallafunctionfromanywhere
withinapage(orevenfromotherpagesifthefunctionisembeddedinanexternal.jsfile).Functionscanbedefined
bothinthe<head>andinthe<body>sectionofadocument.However,toassurethatafunctionisread/loadedby
thebrowserbeforeitiscalled,itcouldbewisetoputfunctionsinthe<head>section.
HowtoDefineaFunction
Syntax
functionfunctionname(var1,var2,...,varX)
{
somecode
}
Theparametersvar1,var2,etc.arevariablesorvaluespassedintothefunction.The{andthe}definesthestartand
endofthefunction.Thewordfunctionmustbewritteninlowercaseletters,otherwiseaJavaScripterroroccurs!
Alsonotethatyoumustcallafunctionwiththeexactsamecapitalsasinthefunctionname
JavaScriptFunctionExample
Example
<html>
<head>
<scripttype="text/javascript">
functiondisplaymessage()
{
alert("HelloWorld!")
}
</script>
</head>
<body>
<form>
<inputtype="button"value="Clickme!"onclick="displaymessage()"/>
</form>
</body>
</html>
ThereturnStatement
Thereturnstatementisusedtospecifythevaluethatisreturnedfromthefunction.So,functionsthataregoingto
returnavaluemustusethereturnstatement.Theexamplebelowreturnstheproductoftwonumbers(aandb):
Example
<html>
<head>
<scripttype="text/javascript">
functionproduct(a,b)
{
returna*b
}
</script>
</head>
<body>
<scripttype="text/javascript">
document.write(product(4,3))
</script>
</body>
</html>
JavaScriptLoops
Oftenwhenyouwritecode,youwantthesameblockofcodetorunoverandoveragaininarow.Insteadofadding
severalalmostequallinesinascriptwecanuseloopstoperformatasklikethis.
InJavaScript,therearetwodifferentkindofloops:
forloopsthroughablockofcodeaspecifiednumberoftimes
whileloopsthroughablockofcodewhileaspecifiedconditionistrue
TheforLoop
Theforloopisusedwhenyouknowinadvancehowmanytimesthescriptshouldrun.
Syntax
for(variable=startvaluevariable<=endvaluevariable=variable+increment)
{
codetobeexecuted
}
Example
Theexamplebelowdefinesaloopthatstartswithi=0.Theloopwillcontinuetorunaslongasiislessthan,orequal
to5.iwillincreaseby1eachtimetheloopruns.
Note:Theincrementparametercouldalsobenegative,andthe<=couldbeanycomparingstatement.
Example
<html>
<body>
<scripttype="text/javascript">
vari=0
for(i=0i<=5i++)
{
document.write("Thenumberis"+i)
document.write("<br/>")
}
</script>
</body>
</html>
JavaScriptWhileLoop
Loopsexecuteablockofcodeaspecifiednumberoftimes,orwhileaspecifiedconditionistrue.
ThewhileLoop
Thewhilelooploopsthroughablockofcodewhileaspecifiedconditionistrue.
Syntax
while(variable<=endvalue)
{
codetobeexecuted
}
Note:The<=couldbeanycomparingoperator.
Example
Theexamplebelowdefinesaloopthatstartswithi=0.Theloopwillcontinuetorunaslongasiislessthan,orequal
to5.iwillincreaseby1eachtimetheloopruns:
Example
<html>
<body>
<scripttype="text/javascript">
vari=0
while(i<=5)
{
document.write("Thenumberis"+i)
document.write("<br/>")
i++
}
</script>
</body>
</html>
Thedo...whileLoop
Thedo...whileloopisavariantofthewhileloop.ThisloopwillexecutetheblockofcodeONCE,andthenitwill
repeattheloopaslongasthespecifiedconditionistrue.
Syntax
do
{
codetobeexecuted
}
while(variable<=endvalue)
Example
Theexamplebelowusesado...whileloop.Thedo...whileloopwillalwaysbeexecutedatleastonce,evenifthe
conditionisfalse,becausethestatementsareexecutedbeforetheconditionistested:
Example
<html>
<body>
<scripttype="text/javascript">
vari=0
do
{
document.write("Thenumberis"+i)
document.write("<br/>")
i++
}
while(i<=5)
</script>
</body>
</html>
ThebreakStatement
Thebreakstatementwillbreaktheloopandcontinueexecutingthecodethatfollowsaftertheloop(ifany).
Example
<html>
<body>
<scripttype="text/javascript">
vari=0
for(i=0i<=10i++)
{
if(i==3)
{
break
}
document.write("Thenumberis"+i)
document.write("<br/>")
}
</script>
</body>
</html>
ThecontinueStatement
Thecontinuestatementwillbreakthecurrentloopandcontinuewiththenextvalue.
Example
<html>
<body>
<scripttype="text/javascript">
vari=0
for(i=0i<=10i++)
{
if(i==3)
{
continue
}
document.write("Thenumberis"+i)
document.write("<br/>")
}
</script>
</body>
</html>
JavaScriptFor...InStatement
Thefor...instatementloopsthroughtheelementsofanarrayorthroughthepropertiesofanobject.
Syntax
for(variableinobject)
{
codetobeexecuted
}
Note:Thecodeinthebodyofthefor...inloopisexecutedonceforeachelement/property.
Note:Thevariableargumentcanbeanamedvariable,anarrayelement,orapropertyofanobject.
Example
Usethefor...instatementtoloopthroughanarray:
Example
<html>
<body>
<scripttype="text/javascript">
varx
varmycars=newArray()
mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]="BMW"
for(xinmycars)
{
document.write(mycars[x]+"<br/>")
}
</script>
</body>
</html>
JavaScriptEvents
EventsareactionsthatcanbedetectedbyJavaScript.
Events
ByusingJavaScript,wehavetheabilitytocreatedynamicwebpages.Eventsareactionsthatcanbedetectedby
JavaScript.EveryelementonawebpagehascertaineventswhichcantriggeraJavaScript.Forexample,wecanuse
theonClickeventofabuttonelementtoindicatethatafunctionwillrunwhenauserclicksonthebutton.Wedefine
theeventsintheHTMLtags.
Examplesofevents:
Amouseclick
Awebpageoranimageloading
Mousingoverahotspotonthewebpage
SelectinganinputfieldinanHTMLform
SubmittinganHTMLform
Akeystroke
Eventsarenormallyusedincombinationwithfunctions,andthefunctionwillnotbeexecutedbeforethe
eventoccurs.
EventAssociation
EventsareassociatedwithHTMLtags.Thedefinitionsoftheeventsdescribedbelowareasfollows:
Eventhandler
Appliesto:
Triggeredwhen:
onAbort
Image
Theloadingoftheimageiscancelled.
onBlur
Button,Checkbox,Password,Radio,Reset,
Theobjectinquestionlosesfocus(e.g.by
Select,Submit,Text,TextArea,Window
clickingoutsideitorpressingtheTABkey).
Select,Text,TextArea
Thedataintheformelementischangedbythe
onChange
user.
onClick
Button,Checkbox,Link,Radio,Reset,Submit
Theobjectisclickedon.
onDblClick
Document,Link
Theobjectisdoubleclickedon.
onError
Image
AJavaScripterroroccurs.
onFocus
Button,Checkbox,Password,Radio,Reset,
Theobjectinquestiongainsfocus(e.g.by
JavaScriptObjects
ObjectorientedProgramminginanimportantaspectofJavaScript.Itispossibletousebuiltinobjectsavailablein
JavaScript.ItisalsopossibleforaJavaScriptprogrammertodefinehisownobjectsandvariabletypes.Inthis
JavaScripttutorial,youwilllearnhowtomakeuseofbuiltinobjectsavailableinJavaScript.
BuiltinobjectsinJavaScript:
SomeofthebuiltinobjectsavailableinJavaScriptare:
Date
Math
String,Number,Boolean
RegExp
window(GlobalObejct)
JavaScriptStringObject
Oftheaboveobjects,themostwidelyusedoneistheStringobject.Objectsarenothingbutspecialkindofdata.
EachobjecthasPropertiesandMethodsassociatedwithit.propertyisthevaluethatistaggedtotheobject.For
exampleletusconsideroneofthepropertiesassociatedwiththemostpopularlyusedStringobjectthelength
property.Lengthpropertyofthestringobjectreturnsthelengthofthestringthatisinotherwordsthenumberof
characterspresentinthestring.
Generalsyntaxofusingthelengthpropertyofthestringobjectisasbelow:
variablename.length
Herevariablenameisthenameofthevariabletowhichthestringisassignedandlengthisthekeyword.
ForexampleconsidertheJavaScriptbelow:
<html>
<body>
<scripttype="text/javascript">
varexf="Welcome"
document.write(exf.length)
</script>
</body>
</html>
Theoutputoftheaboveis
7
MethodofanObject:
Methodofanobjectreferstotheactionsthancanbeperformedontheobject.ForexampleinStringObjectthereare
severalmethodsavailableinJavaScript.
ExampletounderstandhowmethodcanbeusedinanObject.
Intheexamplebelow,wehaveusedtoUpperCasemethodofStringobject.
<html>
<body>
<scripttype="text/javascript">
varexf="Welcome"
document.write(exf.toUpperCase())
</script>
</body>
</html>
Theoutputoftheabovescriptis
WELCOME
IntheabovescriptsincethemethodtoUpperCaseisappliedtothestringobjectexfwhichhasvalueinitializedas
Welcomealllettersgetconvertedasuppercaseandhencetheoutputisasabove.
PurposeofStringObjectinJavaScript:
ThemainpurposeofStringObjectinJavaScriptisforstoringtext.GeneralmethodofusingStringObjectisto
declareavariableandassignastring,inotherwordsatexttothevariable.
varexf="Welcome"
assignsthetextWelcometothevariableexfdefined.
StringObjectMethods
Method
charAt()
charCodeAt()
concat()
indexOf()
lastIndexOf()
match()
replace()
search()
slice()
split()
substr()
Description
Returnsthecharacteratthespecifiedindex
ReturnstheUnicodeofthecharacteratthespecifiedindex
Joinstwoormorestrings,andreturnsacopyofthejoinedstrings
Returnsthepositionofthefirstfoundoccurrenceofaspecifiedvalueinastring
Returnsthepositionofthelastfoundoccurrenceofaspecifiedvalueinastring
Searchesforamatchbetweenaregularexpressionandastring,andreturnsthematches
Searchesforamatchbetweenasubstring(orregularexpression)andastring,andreplaces
thematchedsubstringwithanewsubstring
Searchesforamatchbetweenaregularexpressionandastring,andreturnsthepositionof
thematch
Extractsapartofastringandreturnsanewstring
Splitsastringintoanarrayofsubstrings
Extractsthecharactersfromastring,beginningataspecifiedstartposition,andthroughthe
substring()
toLowerCase()
toUpperCase()
valueOf()
specifiednumberofcharacter
Extractsthecharactersfromastring,betweentwospecifiedindices
Convertsastringtolowercaseletters
Convertsastringtouppercaseletters
ReturnstheprimitivevalueofaStringobject
JavaScriptDateObject
UsageofDateObject:
DateobjectofJavaScriptisusedtoworkwithdateandtimes.GeneralsyntaxfordefiningDateobjectinJavaScript
isasfollows:
varvariablename=newDate()
IntheabovenewisakeywordwhichcreatesaninstanceofobjectandDate()definesvariablenameasDateObject.
Forexample:
varexf=newDate()
Intheaboveexample,variableexfisdefinedasDateobjectwhichhascurrentdateandtimeasitsinitialvalue.
MethodsofDateObject:
SomeofthemethodsavailablewithDateobjectare:
setSeconds()Setsthesecondsforaspecifieddateaccordingtolocaltime.
setMinutes()Setstheminutesforaspecifieddateaccordingtolocaltime.
setHours()Setsthehoursforaspecifieddateaccordingtolocaltime.
setDate()Setsthedayofthemonthforaspecifieddateaccordingtolocaltime.
setMonth()Setsthemonthforaspecifieddateaccordingtolocaltime.
setYear()Setstheyear(deprecated)foraspecifieddateaccordingtolocaltime.
setFullYear()Setsthefullyearforaspecifieddateaccordingtolocaltime.
toString()ReturnsastringrepresentingthespecifiedDateobject.
getSeconds()Returnssecondsinthespecifieddateaccordingtolocaltime.
getMinutes()Returnsminutesinthespecifieddateaccordingtolocaltime.
getHours()Returnshourinthespecifieddateaccordingtolocaltime.
getDay()Returnsdayoftheweekforaspecifieddateaccordingtolocaltime
getDate()Returnsdayofthemonthforaspecifieddateaccordingtolocaltime.
getMonth()Returnsmonthinthespecifieddateaccordingtolocaltime.
getYear()Returnsyear(deprecated)inthespecifieddateaccordingtolocaltime.
getFullYear()Returnsyearofthespecifieddateaccordingtolocaltime.
ExampleforusageofDateObjectmethodsmentionedabove:
varexf=newDate()
exf.setFullYear(2020,0,20)
AswehaveseensetFullYear()isusedforSettingthefullyearforaspecifieddateaccordingtolocaltime.Inthe
aboveexampletheDateobjectexfissettothespecificdateandyear20thJanuary2020
ExampleforusingmethodsofDateObject
<html>
<body>
<scripttype="text/javascript">
varexforsys=newDate()
varcurrentDay=exforsys.getDate()
varcurrentMonth=exforsys.getMonth()+1
varcurrentYear=exforsys.getFullYear()
document.write(currentMonth+"/"+currentDay+
"/"+currentYear)
</script>
</body>
</html>
Outputoftheaboveprogramis:
11/15/2006
JavaScriptMathObject
UsageofMathObject:
JavaScriptMathobjectisusedtoperformmathematicaltasks.ButunliketheStringandtheDateobjectwhich
requiresdefiningtheobject,Mathobjectneednotbedefined.MathobjectinJavaScripthastwomainattributes:
Properties
Methods
PropertiesofMathObject:
TheJavaScripthaseightmathematicalvaluesandthiscanbeaccessedbyusingtheMathObject.Theeight
mathematicalvaluesare:
E
PI
squarerootof2denotedasSQRT2
squarerootof1/2denotedasSQRT1_2
naturallogof2denotedasLN2
naturallogof10denotedasLN10
base2logofEdenotedasLOG2E
base10logofEdenotedasLOG10E
ThewayofaccessingthesevaluesinJavaScriptisbyusingthewordMathbeforethesevaluesnamelyas
Math.E
Math.LOG10Eandsoon
MethodsofMathObject:
TherearenumerousmethodsavailableinJavaScriptforMathObject.Someofthemarementionedbelownamely:
abs(x)Returnsabsolutevalueofx.
acos(x)Returnsarccosineofxinradians.
asin(x)Returnsarcsineofxinradians.
atan(x)Returnsarctanofxinradians.
atan2(y,x)Counterclockwiseanglebetweenxaxisandpoint(x,y).
ceil(x)Returnsthesmallestintegergreaterthanorequaltox.(roundup).
cos(x)Returnscosineofx,wherexisinradians.
exp(x)Returnsex
floor(x)Returnsthelargestintegerlessthanorequaltox.(rounddown)
log(x)Returnsthenaturallogarithm(baseE)ofx.
max(a,b)Returnsthelargerofaandb.
min(a,b)Returnsthelesserofaandb.
pow(x,y)Returnsxy
random()Returnsapseudorandomnumberbetween0and1.
round(x)Roundsxupordowntothenearestinteger.Itrounds.5up.
sin(x)ReturnstheSinofx,wherexisinradians.
sqrt(x)Returnsthesquarerootofx.
tan(x)ReturnstheTanofx,wherexisinradians.
ExampleforMathObjectmethodsmentionedabove:
<html>
<body>
<scripttype="text/javascript">
document.write(Math.round(5.8))
</script>
</body>
</html>
Theoutputoftheaboveprogramis
6
Thisisbecausetheround()methodroundsthenumbergiveninargumentnamelyhere5.8tothenearestinteger.It
rounds.5upwhichgives6.
AnotherexampleforusingMathObjectinJavaScript.
<html>
<body>
<scripttype="text/javascript">
document.write(Math.max(8,9)+"<br/>")
document.write(Math.max(5,3)+"<br/>")
document.write(Math.max(2,7)+"<br/>")
</script>
</body>
</html>
Outputoftheaboveprogramis
9
3
2
Theaboveexampleusesthemax()methodoftheMathobjectwhichreturnsthelargestofthetwonumbersgivenin
argumentsofthemaxmethod.
JavaScriptBooleanObject
TheBooleanobjectisusedtoconvertanonBooleanvaluetoaBooleanvalue(trueorfalse).
BooleanObjectMethods
Method
toString()
valueOf()
Description
ConvertsaBooleanvaluetoastring,andreturnstheresult
ReturnstheprimitivevalueofaBooleanobject
NumberObject
TheNumberobjectisanobjectwrapperforprimitivenumericvalues.
NumberobjectsarecreatedwithnewNumber().
Syntax
varnum=newNumber(value)
NumberObjectMethods
Method
toExponential(x)
toFixed(x)
toPrecision(x)
toString()
valueOf()
Description
Convertsanumberintoanexponentialnotation
Formatsanumberwithxnumbersofdigitsafterthedecimalpoint
Formatsanumbertoxlength
ConvertsaNumberobjecttoastring
ReturnstheprimitivevalueofaNumberobject
StringObject
TheStringobjectisusedtomanipulateastoredpieceoftext.
StringobjectsarecreatedwithnewString().
Syntax
vartxt=newString(string)
ormoresimply:
vartxt=string
WindowObject
Thewindowobjectrepresentsanopenwindowinabrowser.
Ifadocumentcontainframes(<frame>or<iframe>tags),thebrowsercreatesonewindowobjectfortheHTML
document,andoneadditionalwindowobjectforeachframe.
WindowObjectMethods
Method
alert()
blur()
clearInterval()
clearTimeout()
close()
confirm()
createPopup()
focus()
moveBy()
moveTo()
open()
print()
prompt()
resizeBy()
resizeTo()
scroll()
scrollBy()
scrollTo()
setInterval()
setTimeout()
Description
DisplaysanalertboxwithamessageandanOKbutton
Removesfocusfromthecurrentwindow
ClearsatimersetwithsetInterval()
ClearsatimersetwithsetTimeout()
Closesthecurrentwindow
DisplaysadialogboxwithamessageandanOKandaCancelbutton
Createsapopupwindow
Setsfocustothecurrentwindow
Movesawindowrelativetoitscurrentposition
Movesawindowtothespecifiedposition
Opensanewbrowserwindow
Printsthecontentofthecurrentwindow
Displaysadialogboxthatpromptsthevisitorforinput
Resizesthewindowbythespecifiedpixels
Resizesthewindowtothespecifiedwidthandheight
Scrollsthecontentbythespecifiednumberofpixels
Scrollsthecontenttothespecifiedcoordinates
Callsafunctionorevaluatesanexpressionatspecifiedintervals(inmilliseconds)
Callsafunctionorevaluatesanexpressionafteraspecifiednumberofmilliseconds
JavaScriptRegExpObject
Regularexpressionsareusedtodosophisticatedpatternmatching,whichcanoftenbehelpfulinformvalidation.
Forexample,aregularexpressioncanbeusedtocheckwhetheranemailaddressenteredintoaformfieldis
syntacticallycorrect.JavaScriptsupportsPerlcompatibleregularexpressions.
TherearetwowaystocreatearegularexpressioninJavaScript:
1.Usingliteralsyntax
varreExample=/pattern/
2.UsingtheRegExp()constructor
varreExample=newRegExp("pattern")
Assumingyouknowtheregularexpressionpatternyouaregoingtouse,thereisnorealdifferencebetweenthetwo
however,ifyoudon'tknowthepatternaheadoftime(e.g,you'reretrievingitfromaform),itcanbeeasiertouse
theRegExp()constructor.
JavaScript'sRegularExpressionMethods
TheregularexpressionmethodinJavaScripthastwomainmethodsfortestingstrings:test()andexec().
Theexec()Method
Theexec()methodtakesoneargument,astring,andcheckswhetherthatstringcontainsoneormorematchesofthe
patternspecifiedbytheregularexpression.Ifoneormorematchesisfound,themethodreturnsaresultarraywith
thestartingpointsofthematches.Ifnomatchisfound,themethodreturnsnull.
Thetest()Method
Thetest()methodalsotakesoneargument,astring,andcheckswhetherthatstringcontainsamatchofthepattern
specifiedbytheregularexpression.Itreturnstrueifitdoescontainamatchandfalseifitdoesnot.Thismethodis
veryusefulinformvalidationscripts.Thecodesamplebelowshowshowitcanbeusedforcheckingasocial
securitynumber.Don'tworryaboutthesyntaxoftheregularexpressionitself.We'llcoverthatshortly.
CodeSample:RegularExpressionsforvalidatingsocialsecuritynumber
<html>
<head>
<scripttype="text/javascript">
varexp=/^[09]{3}[\]?[09]{2}[\]?[09]{4}$/
functionf1(ssn)
{
if(exp.test(ssn)){alert("VALIDSSN")}
else{alert("INVALIDSSN")}
}
</script>
</head>
<body>
<formname=f1>
<inputtype="text"name="t1"/>
<inputtype="button"value="Check"onclick="f1(this.f1.t1.value)"/>
</form>
</body>
</html>
CodeExplanation
Let'sexaminethecodemoreclosely:
1.First,avariablecontainingaregularexpressionobjectforasocialsecuritynumberisdeclared.
varexp=/^[09]{3}[\]?[09]{2}[\]?[09]{4}$/
2.Next,afunctioncalledf1()iscreated.Thisfunctiontakesoneargument:ssn,whichisastring.Thefunction
thenteststoseeifthestringmatchestheregularexpressionpatternbypassingittotheregularexpressionobject's
test()method.Ifitdoesmatch,thefunctionalerts"VALIDSSN".Otherwise,italerts"INVALIDSSN".
functionf1(ssn)
{
if(exp.test(ssn)){alert("VALIDSSN")}
else{alert("INVALIDSSN")}
}
3.Aforminthebodyofthepageprovidesatextfieldforinsertingasocialsecuritynumberandabuttonthat
passestheuserenteredsocialsecuritynumbertothef1()function.
<form>
<inputtype="text"name="t1"/>
<inputtype="button"value="Check"onclick="checkSsn(this.form.ssn.value)"/>
</form>
Flags
Flagsappearingaftertheendslashmodifyhowaregularexpressionworks.
*Theiflagmakesaregularexpressioncaseinsensitive.Forexample,/aeiou/imatchesalllowercaseand
uppercasevowels.
*Thegflagspecifiesaglobalmatch,meaningthatallmatchesofthespecifiedpatternshouldbereturned.
RegularExpressionSyntax
Aregularexpressionisapatternthatspecifiesalistofcharacters.
StartandEnd:^$
Acaret(^)atthebeginningofaregularexpressionindicatesthatthestringbeingsearchedmuststartwiththis
pattern.
*Thepattern^foocanbefoundin"food",butnotin"barfood".
Adollarsign($)attheendofaregularexpressionindicatesthatthestringbeingsearchedmustendwiththis
pattern.
*Thepatternfoo$canbefoundin"curfoo",butnotin"food".
NumberofOccurrences:?+*{}
Thefollowingsymbolsaffectthenumberofoccurrencesoftheprecedingcharacter:?,+,*,and{}.
Aquestionmark(?)indicatesthattheprecedingcharactershouldappearzerooronetimesinthepattern.
*Thepatternfoo?canbefoundin"food"and"fod",butnot"faod".
Aplussign(+)indicatesthattheprecedingcharactershouldappearoneormoretimesinthepattern.
*Thepatternfo+canbefoundin"fod","food"and"foood",butnot"fd".
Aasterisk(*)indicatesthattheprecedingcharactershouldappearzeroormoretimesinthepattern.
*Thepatternfo*dcanbefoundin"fd","fod"and"food".
Curlybracketswithoneparameter({n})indicatethattheprecedingcharactershouldappearexactlyntimesinthe
pattern.
*Thepatternfo{3}dcanbefoundin"foood",butnot"food"or"fooood".
Curlybracketswithtwoparameters({n1,n2})indicatethattheprecedingcharactershouldappearbetweenn1and
n2timesinthepattern.
*Thepatternfo{2,4}dcanbefoundin"food","foood"and"fooood",butnot"fod"or"foooood".
Curlybracketswithoneparameterandanemptysecondparamenter({n,})indicatethattheprecedingcharacter
shouldappearatleastntimesinthepattern.
*Thepatternfo{2,}dcanbefoundin"food"and"foooood",butnot"fod".
CommonCharacters:.\d\D\w\W\s\S
Aperiod(.)representsanycharacterexceptanewline.
*Thepatternfo.dcanbefoundin"food","foad","fo9d",and"fo*d".
Backslashd(\d)representsanydigit.Itistheequivalentof[09].
*Thepatternfo\ddcanbefoundin"fo1d","fo4d"and"fo0d",butnotin"food"or"fodd".
BackslashD(\D)representsanycharacterexceptadigit.Itistheequivalentof[^09].
*Thepatternfo\Ddcanbefoundin"food"and"foad",butnotin"fo4d".
Backslashw(\w)representsanywordcharacter(letters,digits,andtheunderscore(_)).
*Thepatternfo\wdcanbefoundin"food","fo_d"and"fo4d",butnotin"fo*d".
BackslashW(\W)representsanycharacterexceptawordcharacter.
*Thepatternfo\Wdcanbefoundin"fo*d","fo@d"and"fo.d",butnotin"food".
Backslashs(\s)representsanywhitespacecharacter(e.g,space,tab,newline,etc.).
*Thepatternfo\sdcanbefoundin"fod",butnotin"food".
BackslashS(\S)representsanycharacterexceptawhitespacecharacter.
*Thepatternfo\Sdcanbefoundin"fo*d","food"and"fo4d",butnotin"fod".
Grouping:[]
Squarebrackets([])areusedtogroupoptions.
*Thepatternf[aeiou]dcanbefoundin"fad"and"fed",butnotin"food","faed"or"fd".
*Thepatternf[aeiou]{2}dcanbefoundin"faed"and"feod",butnotin"fod","fed"or"fd".
Negation:^
Whenusedafterthefirstcharacteroftheregularexpression,thecaret(^)isusedfornegation.
*Thepatternf[^aeiou]dcanbefoundin"fqd"and"f4d",butnotin"fad"or"fed".
Subpatterns:()
Parentheses()areusedtocapturesubpatterns.
*Thepatternf(oo)?dcanbefoundin"food"and"fd",butnotin"fod".
Alternatives:|
Thepipe(|)isusedtocreateoptionalpatterns.
*Thepatternfoo$|^barcanbefoundin"foo"and"bar",butnot"foobar".
EscapeCharacter:\
Thebackslash(\)isusedtoescapespecialcharacters.
*Thepatternfo\.dcanbefoundin"fo.d",butnotin"food"or"fo4d".
Amorepracticalexamplehastodomatchingthedelimiterinsocialsecuritynumbers.Examinethefollowing
regularexpression.
^\d{3}([\]?)\d{2}([\]?)\d{4}$
Withinthecaret(^)anddollarsign($),whichareusedtospecifythebeginningandendofthepattern,thereare
threesequencesofdigits,optionallyseparatedbyahyphenoraspace.Thispatternwillbematchedinallof
followingstrings(andmore).
*123456789
*123456789
*123456789
*123456789
*123456789
*123456789
Thelastthreestringsarenotideal,buttheydomatchthepattern.Backreferencescanbeusedtomakesurethatthe
seconddelimitermatchesthefirstdelimiter.Theregularexpressionwouldlooklikethis.
^\d{3}([\]?)\d{2}\1\d{4}$
The\1refersbacktothefirstsubpattern.Onlythefirstthreestringslistedabovematchthisregularexpression.
FormValidationwithRegularExpressions
Regularexpressionsmakeiteasytocreatepowerfulformvalidationfunctions.Takealookatthefollowing
example.
CodeSample:Login.html
<html>
<head>
<scripttype="text/javascript">
varRE_EMAIL=/^(\w+[\\.])*\w+@(\w+\.)+[AZaz]+$/
varRE_PASSWORD=/^[AZaz\d]{6,8}$/
functionvalidate()
{
varemail=form.Email.value
varpassword=form.Password.value
varerrors=[]
if(!RE_EMAIL.test(email)){alert("Youmustenteravalidemailaddress.")}
if(!RE_PASSWORD.test(password)){alert("Youmustenteravalidpassword.")}
}
</script>
</head>
<body>
<formname=form>
Email:<inputtype="text"name="Email"/>
Password:<inputtype="password"name="Password/>
*Passwordmustbebetween6and10charactersandcanonlycontainlettersanddigits.
<inputtype="submit"value="Submit"onclick=Validate()/>
<inputtype="reset"value="ResetForm"/>
</p>
</form>
</body>
</html>
CodeExplanation
Thiscodestartsbydefiningregularexpressionsforanemailaddressandapassword.Let'sbreakeachonedown.
varRE_EMAIL=/^(\w+\.)*\w+@(\w+\.)+[AZaz]+$/
1.Thecaret(^)saystostartatthebeginning.Thispreventstheuserfromenteringinvalidcharactersatthe
beginningoftheemailaddress.
2.(\w+[\\.])*allowsforasequenceofwordcharactersfollowedbyadotoradash.The*indicatesthatthe
patterncanberepeatedzeroormoretimes.Successfulpatternsinclude"ndunn.","ndunn","nat.s.",and"nats".
3.\w+allowsforoneormorewordcharacters.
4.@allowsforasingle@symbol.
5.(\w+\.)+allowsforasequenceofwordcharactersfollowedbyadot.The+indicatesthatthepatterncanbe
repeatedoneormoretimes.Thisisthedomainnamewithoutthelastportion(e.g,withoutthe"com"or"gov").
6.[AZaz]+allowsforoneormoreletters.Thisisthe"com"or"gov"portionoftheemailaddress.
7.Thedollarsign($)saystoendhere.Thispreventstheuserfromenteringinvalidcharactersattheendofthe
emailaddress.
varRE_PASSWORD=/^[AZaz\d]{6,8}$/
1.Thecaret(^)saystostartatthebeginning.Thispreventstheuserfromenteringinvalidcharactersatthe
beginningofthepassword.
2.[AZaz\d]{6,8}allowsforasixtoeightcharactersequenceoflettersanddigits.
3.Thedollarsign($)saystoendhere.Thispreventstheuserfromenteringinvalidcharactersattheendofthe
password.
Exercises:
1. Constructaregexptovalidateatextfieldwhichshouldbeusedtoacceptonlyastringcomposedby3
letters,onespace,6numbers,a""andanumbersuchasMJHJ1234566
Ans:/^[AZaz]{4}\s\d{6}\\d{1}$/
2.Writeregularexpressionstocheckfor:
1.ProperName
ostartswithcapitalletter
ofollowedbyoneormorelettersorapostophes
omaybemultiplewords(e.g,"NewYorkCity")
2.Initial
ozerooronecapitalletters
3.State
otwocapitalletters
4.PostalCode
ofivedigits(e.g,"02138")
opossiblyfollowedbyadashandfourdigits(e.g,"1234")
5.Username
obetween6and15lettersordigits
3.Addvalidationtocheckthefollowingfields:
1.firstname
2.middleinitial
3.lastname
4.city
5.state
6.zip
7.username
3.Testyoursolutioninabrowser.
DocumentObject
EachHTMLdocumentloadedintoabrowserwindowbecomesaDocumentobject.TheDocumentobjectprovides
accesstoallHTMLelementsinapage,fromwithinascript.
DocumentObjectMethods
Method
close()
getElementById()
getElementsByName()
getElementsByTagName()
open()
write()
writeln()
Description
Closestheoutputstreampreviouslyopenedwithdocument.open()
Accessesthefirstelementwiththespecifiedid
Accessesallelementswithaspecifiedname
Accessesallelementswithaspecifiedtagname
Opensanoutputstreamtocollecttheoutputfromdocument.write()or
document.writeln()
WritesHTMLexpressionsorJavaScriptcodetoadocument
Sameaswrite(),butaddsanewlinecharacteraftereachstatement
Arrays
ItdescribestheJavaScriptarrayobjectincludingparameters,properties,andmethods.
Parameters
*arrayLength
*elementNArrayelementlistofvalues
Properties
*index
*input
*lengthThequantityofelementsintheobject.
*prototypeForcreatingmoreproperties.
Methods
*chop()Usedtotruncatethelastcharacterofaallstringsthatarepartofanarray.Thismethodisnotdefinedso
itmustbewrittenandincludedinyourcode.
varexclamations=newArray("Lookout!","Duck!")
exclamations.chop()
Causesthevaluesofexclamationstobecome:
Lookout
Duck
*concat()
*grep(searchstring)Takesanarrayandreturnsthosearrayelementstringsthatcontainmatchingstrings.This
methodisnotdefinedsoitmustbewrittenandincludedinyourcode.
words=newArray("limit","lines","finish","complete","In","Out")
inwords=words.grep("in")
Thearray,inwords,willbe:
lines,finish
*join(delimiter)Putsallelementsinthearrayintoastring,separatingeachelementwiththespecifieddelimiter.
words=newArray("limit","lines","finish","complete","In","Out")
varjwords=words.join("")
Thevalueofthestringjwordsis:
limitlinesfinishcompleteInOut
*pop()Popsthelaststringoffthearrayandreturnsit.Thismethodisnotdefinedsoitmustbewrittenand
includedinyourcode.
words=newArray("limit","lines","finish","complete","In","Out")
varlastword=words.pop()
Thevalueofthestringlastwordis:
Out
*push(strings)Stringsareplacedattheendofthearray.Thismethodisnotdefinedsoitmustbewrittenand
includedinyourcode.
words=newArray("limit","lines","finish")
words.push("complete","In","Out")
Thearray,words,willbe:
limit,lines,finish,complete,In,Out
*reverse()Putsarrayelementsinreverseorder.
words=newArray("limit","lines","finish","complete","In","Out")
words.reverse()
Thearray,words,willbe:
Out,In,complete,finish,lines,limit
*shift()Decreasesarrayelementsizebyonebyshiftingthefirstelementoffthearrayandreturningit.This
methodisnotdefinedsoitmustbewrittenandincludedinyourcode.
words=newArray("limit","lines","finish","complete","In","Out")
word=words.shift()
Thearray,words,willbe:
In,complete,finish,lines,limit
Thestringwordwillbe:
Out
*sort()Sortsthearrayelementsindictionaryorderorusingacomparefunctionpassedtothemethod.
words=newArray("limit","lines","finish","complete","In","Out")
word=words.sort()
Thevalueofwordsbecomes:
In,Out,complete,finish,limit,lines
*splice()Itisusedtotakeelementsoutofanarrayandreplacethemwiththosespecified.Inthebelowexample
theelementstartingatelement3isremoved,twoofthemareremovedandreplacedwiththespecifiedstrings.The
valuereturnedarethosevaluesthatarereplaced.Thismethodisnotdefinedsoitmustbewrittenandincludedin
yourcode.
words=newArray("limit","lines","finish","complete","In","Out")
words1=words.splice(3,2,"done","On")
Thevalueofwordsbecomes:
limit,lines,finish,done,On,Out
Thevalueofwords1issetto:
complete,In
*split(deliimiter)Splitsastringusingthedelimiterandreturnsanarray.
words=newString("limitlinesfinishcompleteInOut")
varswords=words.split("")
Thevaluesinthearrayswordsis:
limit,lines,finish,complete,In,Out
*unshift()Placeselementaatthestartofanarray
words=newArray("finish","complete","In","Out")
word=words.shift("limit","lines")
Thearray,words,willbe:
limit,lines,finish,complete,In,Out
Formvalidation
Form validation is the process of checking that a form has been filled in correctly before it is processed. For
example,ifyourformhasaboxfortheusertotypetheiremailaddress,youmightwantyourformhandlertocheck
thatthey'vefilledintheiraddressbeforeyoudealwiththerestoftheform.Formvalidationisusuallydonewith
JavaScriptembeddedintheWebpage
Validatetextfieldtoacceptemailid
Theaboveprogramwillaccepttheinputinanyoneofthefollowingvalidform
raj@yahoo.com raj.kumar@yahoo.com
raj.k@yahoo.co.in
validatetextfieldtoacceptname
Theaboveprogramwillaccepttheinputonlyinthefollowingvalidform
Rajkumar
Validatetextfieldtoacceptanage
Theaboveprogramwillaccepttheinputonlyinanyoneofthefollowingvalidform
25
5
101
Validateacheckbox
Validateformselection
HostObjects
JavaScriptsupportsthreetypesofobjects:native,host,anduserdefined.Nativeobjectsareobjects
suppliedbytheJavaScriptlanguage.String,Boolean,Math,andNumberareexamplesofnativeobjects.
HostobjectsareJavaScriptobjectsthatprovidespecialaccesstothehostenvironment.Theyareprovided
bythebrowserforthepurposeofinteractionwiththeloadeddocument.Inabrowserenvironment,
1.
2.
window
document
objectsarehostobjects.Severalotherbrowserhostobjectsareinformal,defactostandards.Theyare:alert,
prompt,confirm.
DOM
TheDocumentObjectModel(DOM)isanAPIthatallowsprogramstointeractwithHTML(or
XML)documents
TheprimaryfunctionoftheDocumentObjectModelistoview,access,andchangethestructure
ofanHTMLdocumentseparatefromthecontentcontainedwithinit.
TheDOMwillprovideyouwithmethodsandpropertiestoretrieve,modify,update,anddelete
partsofthedocumentyouareworkingon.ThepropertiesoftheDocumentObjectModelareused
todescribethewebpageordocumentandthemethodsoftheDocumentObjectModelareused
forworkingwithpartsofthewebpage.
InDOM,HTMLdocumentisrepresentedintreelikestructure.Itconstructsahierarchicaltree
structureforaHTMLdocumenttotraverseandtomanipulatethedocument.
Forexample,
<html>
<head>
<title>SampleDocument</title>
</head>
<body>
<h1>AnHTMLDocument</h1>
<p>Thisisa<i>simple</i>document.
</body>
</html>
TheDOMrepresentationofthisdocumentisasfollows:
Thenodedirectlyaboveanodeistheparentofthatnode.Thenodesoneleveldirectlybelowanothernode
arethechildrenofthatnode.Nodesatthesamelevel,andwiththesameparent,aresiblings.Thesetof
nodesanynumberoflevelsbelowanothernodearethedescendantsofthatnode.
Typesofnodes
TherearemanytypesofnodesintheDOMdocumenttreethatspecifieswhatkindofnodeitis.
EveryObjectintheDOMdocumenttreehaspropertiesandmethodsdefinedbytheNodehost
object.
ThefollowingtableliststhenonmethodpropertiesofNodeobject.
ThefollowingtableliststhenodetypescommonlyencounteredinHTMLdocumentsandthenodeType
valueforeachone.
NodeType
nodeType
value
nodeTypeconstant
Element
Node.ELEMENT_NODE
Text
Node.TEXT_NODE
Document
Node.DOCUMENT_NODE
Comment
Node.COMMENT_NODE
DocumentFragmen
t
Node.DOCUMENT_FRAGMENT_NOD
E
11
Attr
Node.ATTRIBUTE_NODE
ThefollowingtableliststhemethodpropertiesofNodeobject.
TraversingaDocument:CountingthenumberofTags
TheDOMrepresentsanHTMLdocumentasatreeofNodeobjects.Withanytreestructure,oneofthe
mostcommonthingstodoistraversethetree,examiningeachnodeofthetreeinturn.Thefollowing
programshowsonewaytodothis.
<html>
<head>
<script>
functioncountTags(n)
{//nisaNode
varnumtags=0//Initializethetagcounter
if(n.nodeType==1)//CheckifnisanElement
numtags++//Incrementthecounterifso
varchildren=n.childNodes//Nowgetallchildrenofn
for(vari=0i<children.lengthi++)
{//Loopthroughthechildren
numtags+=countTags(children[i])//Recurseoneachone
}
returnnumtags//Returnthetotalnumberoftags
}
</script>
</head>
<bodyonload="alert('Thisdocumenthas'+countTags(document)+'tags')">
Thisisa<i>sample</i>document.
</body>
</html>
Output
FindingSpecificElementsinaDocument
Theabilitytotraverseallnodesinadocumenttreegivesusthepowertofindspecificnodes.When
programmingwiththeDOMAPI,itisquitecommontoneedaparticularnodewithinthedocumentora
listofnodesofaspecifictypewithinthedocument.
YoucanusegetElementById()andgetElementsByTagName()methodsofDocumentObjecttoobtaina
listofanytypeofHTMLelement.Forexample,tofindallthetableswithinadocument,you'ddothis:
vartables=document.getElementsByTagName("table")
Thiscodefinds<table>tagsandreturnselementsintheorderinwhichtheyappearinthedocument.
getElementById()tofindaspecificelementwhereasgetElementsByName()returnsanarrayofelements
ratherthanasingleelement.
Thefollowingprogramillustratesthis.
<html>
<head>
<scripttype="text/javascript">
functionf1()
{
alert(document.getElementById("p1").nodeName)
}
</script>
</head>
<body>
<pid="p1">Programiscodedtofindparagraphelementispresentinthedocumentornotusing
itsidattribute</p>
<inputtype="button"value="Find"onclick="f1()"/>
</body>
</html>
Output
IntheaboveprogramthemethodgetElementById()findsthespecificelementandnodeNameisused
propertyreturnthespecificelementname.
ModifyingaDocument:Reversingthenodesofadocument
DOMAPIliesinthefeaturesthatallowyoutouseJavaScripttodynamicallymodifydocuments.The
followingexamplesdemonstratethebasictechniquesofmodifyingdocumentsandillustratesomeofthe
possibilities.
ThefollowingexampleincludesaJavaScriptfunctionnamedreverse(),asampledocument,andanHTML
buttonthat,whenpressed,callsthereverse()function,passingitthenodethatrepresentsthe<body>
elementofthedocument.Thereverse()functionloopsbackwardthroughthechildrenofthesuppliednode
andusestheremoveChild()andappendChild()methodsoftheNodeobjecttoreversetheorderofthose
children.
<html>
<head><title>Reverse</title>
<script>
functionreverse(n){//ReversetheorderofthechildrenofNoden
varkids=n.childNodes//Getthelistofchildren
varnumkids=kids.length//Figureouthowmanychildrenthereare
for(vari=numkids1i>=0i){//Loopbackwardthroughthechildren
varc=n.removeChild(kids[i])//Removeachild
n.appendChild(c)//Putitbackatitsnewposition
}
}
</script>
</head>
<body>
<pre>
paragraph#1
paragraph#2
paragraph#3
</pre>
<form>
<inputtype="button"value="ClickMetoreverse"onclick="reverse(document.body)"/>
</form>
</body>
</html>
whentheuserclicksthebutton,theorderoftheparagraphsandofthebuttonarereversed.
ChangingelementStyle
ThefollowingprogramillustrateshowtochangetheelementstyleusingDOMpropertiesandmethods.
<html>
<head>
<scripttype="text/javascript">
functionf1()
{
document.getElementById("p1").style.backgroundColor="red"
}
</script>
</head>
<body>
<pid="p1">Programiscodedtochangethestyleoftheparagraph</p>
<inputtype="button"value="Change"onclick="f1()"/>
</body>
</html>
ThemethodgetElementById()getstheparagraphelementinthedocumentandthepropertystyleisusedto
changethebackgroundcoloroftheparagraphtoredasshownbelow.
Changingelementstyle
<html>
<head>
<scripttype="text/javascript">
functionf1()
{
varo=document.getElementById("p1")
o.style.color="red"
}
functionf2()
{
varo=document.getElementById("p1")
o.style.color="blue"
}
</script>
</head>
<body>
<pid="p1">
ClickMe
</p>
<form>
<inputtype=buttonid="b1"value="RED"onclick=f1()/>
<inputtype=buttonid="b2"value="BLUE"onclick=f2()/>
</form>
</body>
</html>
Output
ChangingHTMLContent
ThispageshowsaexampleofhowtochangeaHTMLpage'scontent
<html>
<head>
<scripttype="text/javascript">
functionf1()
{
document.getElementById("p1").childNodes[0].nodeValue="Fine,thankyou."
}
functionf2()
{
document.getElementById("p1").childNodes[0].nodeValue="Howareyou?"
}
</script>
</head>
<bodyid="p1">
<pre>
<inputtype="button"id="b1"value="Question"onclick=f1()/>
<inputtype="button"id="b2"value="Answer"onclick=f2()/>
</pre>
</body>
</html>
AfterpressingtheQuestionbutton,itaddsthecontent,Howareyou?totheHTMLdocumentandafter
pressingtheAnswerbutton,itreplacesthecontentHowareyou?withFine,thankyou
RemovingElementfromHTMLdocuments
<html>
<head>
<scripttype="text/javascript">
functionf1()
{
varnode=document.getElementById("p1")
node.removeChild(node.childNodes[0])
}
</script>
</head>
<body>
<preid="p1"><inputtype="button"id="b1"value="Question"/>
<inputtype="button"id="b2"value="Remove"onclick=f1()/>
ExampleforRemovinganelementfromHTMLdocument.
</pre>
</body>
</html>
AfterpressingtheRemovebutton,theelementQuestionisremovedfromthedocument.
ServersideProgramming:Servlet
Thecombinationof
HTML
JavaScript
DOM
issometimesreferredtoasDynamicHTML(DHTML).Webpagesthatincludescriptingareoftencalled
dynamicpages.Similarly,webserverresponsecanbestaticordynamic
Static:HTMLdocumentisretrievedfromthefilesystembytheserverandthesame
returnedtotheclient.
Dynamic:Inserver,aHTMLdocumentisgeneratedbyaprograminresponsetoan
HTTPrequest
Javaservletsareonetechnologyforproducingdynamicserverresponses.Servletisaclassinstantiatedby
theservertoproduceadynamicresponse.
ServletOverview
Thefollowingfigureillustratestheservletprogramworkingprinciple.
1.
2.
3.
4.
5.
Whenserverstartsitinstantiatesservlets
ServerreceivesHTTPrequest,determinesneedfordynamicresponse
Serverselectstheappropriateservlettogeneratetheresponse,createsrequest/responseobjects,
andpassesthemtoamethodontheservletinstance
Servletaddsinformationtoresponseobjectviamethodcalls
ServergeneratesHTTPresponsebasedoninformationstoredinresponseobject
TypesofServlet
GenericServlet
HttpServlet
Servletsvs.JavaApplications
Servletsdonothaveamain()method
EntrypointtoservletcodeisviacalltoamethoddoGet()/doPost()
Servletinteractionwithenduserisindirectviarequest/responseobjectAPIs
PrimaryservletoutputistypicallyHTML
RunningServlets
1.
2.
3.
4.
Compileservlet(makesurethatJWSDPlibrariesareonpath)
Copy.classfiletoshared/classesdirectory
(Re)starttheTomcatwebserver
IftheclassisnamedServletHello,browseto
http://localhost:8080/servlet/ServletHello
WhatareServlets?
JavaServletsareprogramsthatrunonaWeborApplicationserverandactasamiddlelayerbetweena
requestcomingfromaWebbrowserorotherHTTPclientanddatabasesorapplicationsontheHTTP
server.
UsingServlets,youcancollectinputfromusersthroughwebpageforms,presentrecordsfromadatabase
oranothersource,andcreatewebpagesdynamically.
JavaServletsoftenservethesamepurposeasprogramsimplementedusingtheCommonGatewayInterface
(CGI).ButServletsofferseveraladvantagesincomparisonwiththeCGI.
Performanceissignificantlybetter.
ServletsexecutewithintheaddressspaceofaWebserver.Itisnotnecessarytocreateaseparate
processtohandleeachclientrequest.
ServletsareplatformindependentbecausetheyarewritteninJava.
Javasecuritymanagerontheserverenforcesasetofrestrictionstoprotecttheresourcesona
servermachine.Soservletsaretrusted.
ThefullfunctionalityoftheJavaclasslibrariesisavailabletoaservlet.Itcancommunicatewith
applets,databases,orothersoftwareviathesocketsandRMImechanismsthatyouhaveseen
already.
ServletsArchitecture:
FollowingdiagramshowsthepositionofServeltsinaWebApplication.
ServletsTasks:
Servletsperformthefollowingmajortasks:
1.
2.
3.
4.
5.
Readtheexplicitdatasentbytheclients(browsers).ThisincludesanHTMLformonaWebpage
oritcouldalsocomefromanappletoracustomHTTPclientprogram.
ReadtheimplicitHTTPrequestdatasentbytheclients(browsers).Thisincludescookies,media
typesandcompressionschemesthebrowserunderstands,andsoforth.
Processthedataandgeneratetheresults.Thisprocessmayrequiretalkingtoadatabase,executing
anRMIorCORBAcall,invokingaWebservice,orcomputingtheresponsedirectly.
Sendtheexplicitdata(i.e.,thedocument)totheclients(browsers).Thisdocumentcanbesentina
varietyofformats,includingtext(HTMLorXML),binary(GIFimages),Excel,etc.
SendtheimplicitHTTPresponsetotheclients(browsers).Thisincludestellingthebrowsersor
otherclientswhattypeofdocumentisbeingreturned(e.g.,HTML),settingcookiesandcaching
parameters,andothersuchtasks.
ServletsPackages:
JavaServletsareJavaclassesrunbyawebserverthathasaninterpreterthatsupportstheJavaServlet
specification.
Servletscanbecreatedusingthejavax.servletandjavax.servlet.httppackages,whichareastandardpart
oftheJava'senterpriseedition,anexpandedversionoftheJavaclasslibrarythatsupportslargescale
developmentprojects.
TheseclassesimplementtheJavaServletandJSPspecifications.Atthetimeofwritingthistutorial,the
versionsareJavaServlet2.5andJSP2.1.
JavaservletshavebeencreatedandcompiledjustlikeanyotherJavaclass.Afteryouinstalltheservlet
packagesandaddthemtoyourcomputer'sClasspath,youcancompileservletswiththeJDK'sJava
compileroranyothercurrentcompiler.
ServletsLifeCycle
Aservletlifecyclecanbedefinedastheentireprocessfromitscreationtillthedestruction.Thefollowing
arethepathsfollowedbyaservlet
Theservletisinitializedbycallingtheinit()method.
Theservletcallsservice()methodtoprocessaclient'srequest.
Theservletisterminatedbycallingthedestroy()method.
Finally,servletisgarbagecollectedbythegarbagecollectoroftheJVM.
Nowletusdiscussthelifecyclemethodsindetails.
Theinit()method:
Theinitmethodisdesignedtobecalledonlyonce.Itiscalledwhentheservletisfirstcreated,andnot
calledagainforeachuserrequest.So,itisusedforonetimeinitializations,justaswiththeinitmethodof
applets.
TheservletisnormallycreatedwhenauserfirstinvokesaURLcorrespondingtotheservlet,butyoucan
alsospecifythattheservletbeloadedwhentheserverisfirststarted.
Whenauserinvokesaservlet,asingleinstanceofeachservletgetscreated,witheachuserrequest
resultinginanewthreadthatishandedofftodoGetordoPostasappropriate.Theinit()methodsimply
createsorloadssomedatathatwillbeusedthroughoutthelifeoftheservlet.
Theinitmethoddefinitionlookslikethis:
publicvoidinit()throwsServletException{
//Initializationcode...
}
Theservice()method:
Theservice()methodisthemainmethodtoperformtheactualtask.Theservletcontainer(i.e.web
server)callstheservice()methodtohandlerequestscomingfromtheclient(browsers)andtowritethe
formattedresponsebacktotheclient.
Eachtimetheserverreceivesarequestforaservlet,theserverspawnsanewthreadandcallsservice.
Theservice()methodcheckstheHTTPrequesttype(GET,POST,PUT,DELETE,etc.)andcallsdoGet,
doPost,doPut,doDelete,etc.methodsasappropriate.
Hereisthesignatureofthismethod:
publicvoidservice(ServletRequestrequest,
ServletResponseresponse)
throwsServletException,IOException{
}
Theservice()methodiscalledbythecontainerandservicemethodinvokesdoGe,doPost,doPut,
doDelete,etc.methodsasappropriate.Soyouhavenothingtodowithservice()methodbutyouoverride
eitherdoGet()ordoPost()dependingonwhattypeofrequestyoureceivefromtheclient.
ThedoGet()anddoPost()aremostfrequentlyusedmethodswithineachservicerequest.Herearethe
signatureofthesetwomethods.
ThedoGet()Method
AGETrequestresultsfromanormalrequestforaURLorfromanHTMLformthathasnoMETHOD
specifiedanditshouldbehandledbydoGet()method.
publicvoiddoGet(HttpServletRequestrequest,
HttpServletResponseresponse)
throwsServletException,IOException{
//Servletcode
}
ThedoPost()Method
APOSTrequestresultsfromanHTMLformthatspecificallylistsPOSTastheMETHODanditshouldbe
handledbydoPost()method.
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
//Servletcode
}
Thedestroy()method:
Thedestroy()methodiscalledonlyonceattheendofthelifecycleofaservlet.Thismethodgivesyour
servletachancetoclosedatabaseconnections,haltbackgroundthreads,writecookielistsorhitcountsto
disk,andperformothersuchcleanupactivities.
Afterthedestroy()methodiscalled,theservletobjectismarkedforgarbagecollection.Thedestroy
methoddefinitionlookslikethis:
publicvoiddestroy(){
//Finalizationcode...
}
ArchitectureDiagram:
Thefollowingfiguredepictsatypicalservletlifecyclescenario.
FirsttheHTTPrequestscomingtotheserveraredelegatedtotheservletcontainer.
Theservletcontainerloadstheservletbeforeinvokingtheservice()method.
Thentheservletcontainerhandlesmultiplerequestsbyspawningmultiplethreads,eachthread
executingtheservice()methodofasingleinstanceoftheservlet.
Structureofaservletprogram
importjava.io.*
importjavax.servlet.*
importjavax.servlet.http.*
publicclassNewServletextendsHttpServlet
{
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException
{
response.setContentType("text/html")
//contenttypeoftheresponse
PrintWriterout=response.getWriter()
//usedtocreatearesponseasaHtmldoc
try{
out.println("<html>")
out.println("</html>")
}catch(Exceptione){}
}
}
}
ServletsExamples
ServletsareJavaclasseswhichserviceHTTPrequestsandimplementthejavax.servlet.Servletinterface.
Webapplicationdeveloperstypicallywriteservletsthatextendjavax.servlet.http.HttpServlet,anabstract
classthatimplementstheServletinterfaceandisspeciallydesignedtohandleHTTPrequests.
SampleCodeforHelloWorld:
FollowingisthesamplesourcecodestructureofaservletexampletowriteHelloWorld:
//Importrequiredjavalibraries
importjava.io.*
importjavax.servlet.*
importjavax.servlet.http.*
//ExtendHttpServletclass
publicclassHelloWorldextendsHttpServlet{
privateStringmessage
publicvoidinit()throwsServletException
{
//Dorequiredinitialization
message="HelloWorld"
}
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException
{
//Setresponsecontenttype
response.setContentType("text/html")
//Actuallogicgoeshere.
PrintWriterout=response.getWriter()
out.println("<html><body><b>"+message+</b></body></html>")
out.close()
}
publicvoiddestroy(){}
}
Output:
finallytypehttp://localhost:8080/HelloWorldinbrowser'saddressbox.If
everythinggoesfine,youwouldgetfollowingresult:
ParameterdataandQueryStrings
ServlethasmethodstoaccessdatacontainedinHTTPRequest(URL)senttotheserverfromthebrowser.
TheQueryStringportionoftheHTTPrequestissocalledparameterdata.Forexample,
http://www.example.com/servlet/PrintThis?name=Raj&color=Red
wheretheportionafterthe?iscalledaquerystring.Hereitisname=Raj&color=Red,inwhichnameand
colorareparameternamesandRajandRedareparametervalues.Printthisisaservletfilenameand
serveltisadirectory.Multipleparametersareseparatedby&.Allparametervaluesarestringsbydefault.
Parameternamesandvaluescanbeany8bitcharacters.
Thefollowingmethodsareusedtoprocesstheseparameterdatainsevlets.
Thefollowingprogramexplainshowtoprocesstheseparameternamesandvaluesaswellaspathofthe
resourceusingservlet.
Exampleprogram
importjava.io.*
importjava.util.*
importjavax.servlet.*
importjavax.servlet.http.*
publicclassNewServletextendsHttpServlet
{
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException
{
response.setContentType("text/html)
PrintWriterout=response.getWriter()
try{
out.println("<html>")
out.println("<head>")
out.println("<title>ServletNewServlet</title>")
out.println("</head>")
out.println("<body>")
out.println("ServletfileNewServletisat:"+request.getContextPath())
Enumerationpara1=request.getParameterNames()
while(para1.hasMoreElements())
{
out.println("Parametername:"+para1.nextElement())
}
Stringname=request.getParameter("name")
Stringid=request.getParameter("id")
out.println("Name:"+name)
out.println("Id:"+id)
out.println("</body>")
out.println("</html>")
}catch(Exceptione){}
}
}
}
ThemethodgetContextPath()ofHttpServeltRequestobjectisusedtogetthelocationoftheresource
ThemethodgetParameter()isusedtogetthevalueoftheparameter.ThemethodgetParameterNames()is
usedtoreturntheparanameternamesaswell.Itreturnsenumeration.Thefollowingcodeintheabove
programisusedtoretrievetheparameternamesfromtheenumeration.
Enumerationpara1=request.getParameterNames()
while(para1.hasMoreElements())
{
out.println("Parametername:"+para1.nextElement())
}
Output:
FormsandParameterdata:(PassingvaluesfromHTMLdocumenttoServlet)
Aformautomaticallygeneratesaquerystringwhensubmitted.Theparameternamespecifiedbyvalueof
nameattributesofformcontrols.Forexample,
whereusernameistheparametername.
Parametervaluecanbethevalueofvalueattributeofanyformcontroloritmaybethevaluereceivedfrom
theuserbythecontrolatruntime.Forexample,
Thefollowingprogramexplainshowtosendthedatatoserverfromawebpageandthesamehowto
receiveitfromtheserver.
Htmlforcreatingawebpage
<html>
<head>
</head>
<body>
<pre>
<formaction="NewServlet"method="post">
FirstName:<inputtype="text"name="t1"/>
LastName:<inputtype="text"name="t2"/>
Age:<inputtype="text"name="t3"/>
Email:<inputtype="text"name="t4"/>
<inputtype="submit"value="Submit"/>
<form>
</pre>
</body>
</html>
Servletforprocessingthedatacomingfromthiswebpage
importjava.io.*
importjavax.servlet.*
importjavax.servlet.http.*
publicclassNewServletextendsHttpServlet{
publicvoidgoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
response.setContentType("text/html")
PrintWriterout=response.getWriter()
try{
out.println("<html>")
out.println("<head>")
out.println("<title>ServletNewServlet</title>")
out.println("</head>")
out.println("<body>")
Strings1=request.getParameter("t1")
Strings2=request.getParameter("t2")
Strings3=request.getParameter("t3")
Strings4=request.getParameter("t4")
out.println("FirstName:"+s1)
out.println("LastName:"+s2)
out.println("Age:"+s3)
out.println("Email:"+s4)
out.println("</body>")
out.println("</html>")
}catch(Exceptione){}
}
}
Output
GETvs.POSTmethodforforms:
GET:
POST:
ItisusedtoprocessthequerystringwhichispartofURL
Ifthelengthofquerystringislimiteditmaybeused.
Itisrecommendedwhenparameterdataisnotstoredbutusedonlytorequestinformation.
Itisusedtoprocessthequerystringaswellastostorethedataonserver.
IftheQuerystringissentasbodyofHTTPrequest,thepostmethodwillbeusedtoretrieve.
Ifthelengthofquerystringisunlimited,itcanbeused
Itisrecommendedifparameterdataisintendedtocausetheservertoupdatestoreddata
MostbrowserswillwarnyouiftheyareabouttoresubmitPOSTdatatoavoidduplicateupdates
Importantnote:
FortheHTTPSession,Cookies,URLrewritinguseour
classnotes.Thesoftcopyforthesetopicswillbegivenlater.