Tải bản đầy đủ - 0 (trang)
Chapter 18. Forms and Form Elements

Chapter 18. Forms and Form Elements

Tải bản đầy đủ - 0trang

submission)whenclicked.

Examplesthroughoutthisbookhavealsoshownthatevent

handlersareoftenthecentralelementofaJavaScriptprogram.

Someofthemostcommonlyusedeventhandlersarethose

usedwithformsorformelements.Thischapterintroducesthe

JavaScriptFormobjectandthevariousJavaScriptobjectsthat

representformelements.Itconcludeswithanexamplethat

illustrateshowyoucanuseJavaScripttovalidateuserinputon

theclientbeforesubmittingittoaserver-sideprogramrunning

onthewebserver.



18.1.TheFormObject

TheJavaScriptFormobjectrepresentsanHTMLform.As

explainedinChapter15,Formobjectsareavailableaselements

oftheforms[]array,whichisapropertyoftheDocumentobject.

Formsappearinthisarrayintheorderinwhichtheyappear

withinthedocument.Thus,document.forms[0]referstothefirst

forminadocument.Youcanrefertothelastformina

documentwiththefollowing:

document.forms[document.forms.length-1]



ThemostinterestingpropertyoftheFormobjectisthe

elements[]array,whichcontainsJavaScriptobjects(ofvarious

types)thatrepresentthevariousinputelementsoftheform.

Again,elementsappearinthisarrayinthesameorderthey

appearinthedocument.Youcanrefertothethirdelementof

thesecondforminthedocumentofthecurrentwindowlike

this:

document.forms[1].elements[2]



TheremainingpropertiesoftheFormobjectareofless

importance.Theaction,encoding,method,andtargetproperties

corresponddirectlytotheaction,encoding,method,andtarget

attributesofthe
tag.Thesepropertiesandattributesare

allusedtocontrolhowformdataissubmittedtothewebserver

andwheretheresultsaredisplayed;theyarethereforeuseful

onlywhentheformisactuallysubmittedtoaserver-side

program.SeeabookonHTMLorserver-sidewebprogramming

forathoroughdiscussionoftheseattributes.Whatisworth

notinghereisthattheseFormpropertiesareallread/write



strings,soaJavaScriptprogramcandynamicallysettheir

valuesinordertochangethewaytheformissubmitted.

InthedaysbeforeJavaScript,aformwassubmittedwitha

special-purposeSubmitbutton,andformelementshadtheir

valuesresetwithaspecial-purposeResetbutton.The

JavaScriptFormobjectsupportstwomethods,submit()and

reset(),thatservethesamepurpose.Invokingthesubmit()

methodofaFormsubmitstheform,andinvokingreset()resets

theformelements.

Toaccompanythesubmit()andreset()methods,theFormobject

providestheonsubmiteventhandlertodetectformsubmission

andtheonreseteventhandlertodetectformresets.Theonsubmit

handlerisinvokedjustbeforetheformissubmitted;itcan

cancelthesubmissionbyreturningfalse.Thisprovidesan

opportunityforaJavaScriptprogramtochecktheuser'sinput

forerrorsinordertoavoidsubmittingincompleteorinvaliddata

overthenetworktoaserver-sideprogram.Youcanfindan

exampleofsucherrorcheckingattheendofthischapter.Note

thattheonsubmithandleristriggeredonlybyagenuineclickon

aSubmitbutton.Callingthesubmit()methodofaformdoesnot

triggertheonsubmithandler.

Theonreseteventhandlerissimilartotheonsubmithandler.Itis

invokedjustbeforetheformisreset,anditcanpreventthe

formelementsfrombeingresetbyreturningfalse.Thisallowsa

JavaScriptprogramtoaskforconfirmationofthereset,which

canbeagoodideawhentheformislongordetailed.Youmight

requestthissortofconfirmationwithaneventhandlerlikethe

following:




onreset="returnconfirm('ReallyeraseALLdataandstartov

>



Liketheonsubmithandler,onresetistriggeredonlybyagenuine

Resetbutton.Callingthereset()methodofaformdoesnot

triggeronreset.



18.2.DefiningFormElements

HTMLformelementsallowyoutocreatesimpleuserinterfaces

foryourJavaScriptprograms.Figure18-1showsacomplex

formthatcontainsatleastoneofeachofthebasicform

elements.IncaseyouarenotalreadyfamiliarwithHTMLform

elements,thefigureincludesanumberedkeyidentifyingeach

typeofelement.Thissectionconcludeswithanexample

(Example18-1)thatshowstheHTMLandJavaScriptcodeused

tocreatetheformpicturedinFigure18-1andtohookupevent

handlerstoeachformelement.



Figure18-1.HTMLformelements



Table18-1liststhetypesofformelementsthatareavailableto

HTMLdesignersandJavaScriptprogrammers.Thefirstcolumn

ofthetablenamesthetypeofformelement,thesecond

columnshowstheHTMLtagsthatdefineelementsofthattype,

andthethirdcolumnliststhevalueofthetypepropertyforeach

typeofelement.Asshownearlier,eachFormobjecthasan

elements[]arraythatcontainstheobjectsthatrepresentthe

form'selements.Eachelementhasatypepropertythatcan

distinguishonetypeofelementfromanother.Byexaminingthe

typepropertyofanunknownformelement,JavaScriptcodecan

determinethetypeoftheelementandfigureoutwhatitcando

withthatelement.Finally,thefourthcolumnofthetable

providesashortdescriptionofeachelementandalsoliststhe

mostimportantormostcommonlyusedeventhandlerforthat

elementtype.

Table18-1.HTMLformelements

Object



HTMLtag



type

property



Descriptionandevents



Button





or
type="button">



"button"



Apushbutton;onclick.



Checkbox type="checkbox">






"checkbox"



Atogglebuttonwithoutradio-buttonbehavior;

onclick.



File







"file"



Aninputfieldforenteringthenameofafileto

uploadtothewebserver;onchange.



Hidden







"hidden"



Datasubmittedwiththeformbutnotvisibleto

theuser;noeventhandlers.



Option













18.3.ScriptingFormElements

TheprevioussectionlistedtheformelementsprovidedbyHTML

andexplainedhowtoembedtheseelementsinyourHTML

documents.Thissectiontakesthenextstepandshowsyouhow

youcanworkwiththoseelementsinyourJavaScriptprograms.



18.3.1.NamingFormsandFormElements

Everyformelementhasanameattributethatmustbesetinits

HTMLtagiftheformistobesubmittedtoaserver-side

program.Whileformsubmissionisnotnecessarilyofinterestto

JavaScriptprograms,thereisanotherusefulreasontospecify

thisnameattribute,asyou'llseeshortly.

The
tagitselfalsohasanameattributethatyoucanset.

Thisattributehasnothingtodowithformsubmission.As

describedinChapter15,itexistsfortheconvenienceof

JavaScriptprogrammers.Ifthenameattributeisdefinedina

tag,whentheFormobjectiscreatedforthatform,itis

storedasanelementintheforms[]arrayoftheDocument

object,asusual,anditisalsostoredinitsownpersonal

propertyoftheDocumentobject.Thenameofthisnewly

definedpropertyisthevalueofthenameattribute.InExample

18-1,forinstance,aformisdefinedwiththistag:





ThisallowsyoutorefertotheFormobjectas:

document.everything



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 18. Forms and Form Elements

Tải bản đầy đủ ngay(0 tr)

×