You are on page 1of 33
quote. back to the server. a specific circumstance (su You can use JavaScript & feents are actions that users perform. For generated. Javascrip’s interaction with HTML is browser manipulates a page- When the page loads, itis Other examples include even ue Write JavaScript to design a fo to design a form to accept input values for the given problem. vents to solve the given problem, ‘ssgn specified atrbute value to the given form contol n with specified parameters {Use Javascript to implement form ¢ © Develop JavaScript to dynamically BH Use the given intrinsic fu ‘To understand Basic Concepts of Forms in JavaScript To study various Form Control Elements with Example i) To learn Events and Event Handling in JavaScript INTRODUCTION. ee Forms are one of the most common webpage elements used with JavaScript. JavaScripts commonly used with forms for following two reasons: 1 Toadd functionality that makes forms easier for users to flout and 2. To validate or process the data that a user enters before that data is submitted to a server side script Javascript Form object represents an HTML form, HTML forms are a very powerful tool for Interacting with users Forms provide you with a way of grouping together HTML interaction elements with a common pur- pose. For example, form may contain elements that enable the input ofa user's data for registering go a web site, Another form may contain elements that enable the user to ask fora bike insurance IML forms serve the purpose of collecting information provided by the visitors, which is later sent One ofthe primary ways in which JavaScript is executed on aweb pages through events, An events peat ‘ch as an action performed by a user or an action performed by the Brevret thats monitored by Javascript and that your script can respond tin someway. vents to allow users to interact with your web pages, The most common jxample, when a ser clicks a form button a click event is is handled through events that occur when the user or the ‘called an event. When the user clicks a button, that click too is an event. ts like pressing any Key, closing awindow, resizing a window, etc. Ninn i, Schnee —————_s a ee form are 4. id: The unique identifier 2 mame: The name, its role i, valent to that of Identifier but forthe functions of DOM, because themethod getementayiss sara tht Mest bt forthe fanctins of DOM, bee 8 action: The name of The ame de he the frm thatthe names and vain of the graphic ometeno at A. onsubmlts Event fed up when the fom canallowto determine Itheseien Baample: orm nanesy fore oasecte dices TheonSubmit attribute associates at dttaarenot sent we tay on tesanerany + A form element that can be represented ts a et box. password tent ox check bux, radlo futon submit button, rece button hidden input fie inage whl ac as ssn buon) Meee Tecorgenerabuton Folowing al its TM frm eens a script to i submit button ee nbmited with a submit button. Note iven automatically in parameter to se submitted and before the execution ofthe action, It ust be executed oF not, ‘{ae'myforn* actione"page.html* onSubnite'test()*> test function on the form I the function return false, the form ‘avant tonal niet — [paseo i “file “onchange "An input held for entering the a ge eee wnidden"> | ‘Data submitted with the form k. a ea a ‘object, event handlers are an eee Perr ard | onchange ‘An input field for password — rar se ee “ a5 ‘button behaviour where only ie Se se = ‘onclick "A push button that resets a SS cee which one iter may be selected eee - Sree eae oe ‘tems may be selected (also see “select Galect multiple tenorea> as an element of the the document form) array. The Ut lds, chechbove hones oo) ae collected th aay ke bet end/writstrng that yes the action tebe ofthe lewents() | An array containing allaf th ofthe orn Use io ap og of the elements of em ene ing Rend write string that species enc eae pels how the form data ene [The numberof elements inthe form rc rethoe Read/erite tring th 3 = [Heute nsng a pero te i emo ‘The name ofthe arget fame or window forms oe submited reset() | Resets the form. subeit() | Submitsaform. tacigien t Forms and the ements tnethods like getElementByid0 a 4 getElementByid Method! t Mireturs a reference tothe element by i810. 1 Following i the syntax of gtElement®y repent = document petzlenent6yZd(36); winere eis reference tan lement tect ot maifan cnet is the document aise case-sensitive tring representing the) unique Df the element being sought jame Method: arjecton of elements with the the specified 1D snot in + ESC ran tenement given tag name.The complete document it var el where © elements is alive © nameis a string repre rmentsin the order they appear in the fre n of foundele ents. The special string ruucllectio 2 the name of the elem B] itioasign vaweseit©> ceri fanction assign) i © sccamant.gettLewunttyle(“title") values “scripting Technology 2 ocomentsgettlenentayla("author').valve = "Meenas : > eyseripo. btn” values"Assign Values" onclic ‘Bamplez: Addressing component direc cheal> oes 4p Ade"panel">

ob ‘liptpple (a 1ge"Stem">anana elivsrapess/ob> ab “uiotang cseript ‘var seni = document. getElenentByZd( "Itemt” ) ; Var elees = document. gettlenentsyTagNane( °1"") ; var item? = eleasl 4]: ocusent.writeln( “Total Wo. List Items: "+ elens.Length) ; ocunent write(“cbeoSpecific Tten One: " + itert.innerText) document rite ("Specific Tten Two: * + item2.imerText) ; eiscript> ‘A TextArea object represents fledoften within an HTM forme” THE stoxtarens element that crests & mulling text Jnput th intone i ease = som nl seas gee So cer see eS se 4 ae fens om one per oy EM te tn i es Bernat ee ware ‘an enter a large amount of text, An ‘This tag is also exactly similar in itsusage with nan Fe, The default font of ext area Is fxed Following table shows the attributes of “textarea names"connents™ colsed@ rowse6> cols indicate how many characters: wide the textarea should be. Rows Indicate how many rows should be present inthe textarea It does not set any limit to how much text can be typed in, it just sets how much area is visible wrap describes how the textarea | clertares nanes"coments wrap=sof®> ‘wraps at the end of lines, ae Soft: 1t wraps long lines in the text area for easy editing, It does hot send the carriage return to the server Hard: It looks similar to soft, but ft sends the carriage returns to the server, Off, Off does not wrap at all. It just displays and sends the text [| entree __ ee Eaample: tab Pests ciel ‘iheat> aoa for neti" Messe: rT gessase” oleae ee eee cor 2 pareese” vue npost” actions" post” o5tyTest messagec/textarea> ot Enter value of checkbox aarae ed checkboxes are an integral part of forms that allow a user fo make selection with = simple click ofthe mouse — You can prompt users for spe maybe checked by the user accord! ent with the ==" ‘checkbox is created by using the input eleme mats checked or unchecked) andisindependent ofthe stateof ‘AcheeKbor in a form has only twos ___ other check boxes in the form. to Sooxes can be grouped together under a common name. Bample: é
eeaceonssien valuese/title? =, een went ota, nen favourite ult OT. a Si pt oats se em i peo or /2cor 2 eee sor ue typeset” va ¢ "ent Bete Lomentay14(s oh document. gett enenttytd( or COS aT Cromer ate : enge ane"); atebles*); hs Lae) A€ CformiPruttat 1 checked) SUSMerY $= FORFAR TVR OE . CA oval H Panel. innertat « ite Frutts are:t + summa AF (Gocument. getELenentaytu ttre m4 panel. AnnecHTM += * vour Favertte Color 45: ; as Co eee: ct ee ve igevptn” types"button” values"Confire choices” onclicke"pol1()" e en” ty a &p id="panel”>

utp: Banana Orange Your Favorite Fruits Your Favorite Color BIvE choices to the ag, which displays a graphical ist of ‘1 iL Deth option ons N

‘amples ena “ches atitle chi> Registration Page egsstration nttp://niraiipeb “input typ input type="text" nanes First name: Last name Password: goa" chandigadh > oo you want sore {nf er sae" cations.con/registration html"? thanen*reainane® />
sirname” (>
cbr/> sd" nane="pass"/>

tex sex" values'"/> Male vev"oex" value="F7/> Fenalechr/?
se nanes"city"> south? ores =332°> kanya xerelac/option? jeunari yoreinfo" />cor/>
Event is ee Function reac . eC) sere (PLease ent fr any vale); » oo <fom renter thn” tego os ye="click mouse here™ > a a «neo os tpt [gexmawse hon rent Object and Event Listeners: 7% Be renin bn oe ee = jeve it in script. An event listener is essentially a mechanism | ame nen fee anion that src het torso eis Don event model when an event xrurs a insta venation about the eve including te io ve crependng other et nce fast object amet Events crested Mis instance contains in . 2 ye of event | ‘mouseover, iene rctrece 1 tbeco a spent this node is called the event arget She Event instance properties type and art = Petaner is ceated, iis sent to certain event De Baa cevccrpe version of the DOM, neva Metis SE fgument that is an instance Tho the addbventstene teociatesan event listener witha gon tat node ‘The syntax of ‘addEventListener() ™* aciment advent istener (vert where ict pare suv string which species the smmousedown’) sve wart toca Be secood parameter isthe Fun cet B Berend ean eres 5s optional The it Hep eam en ere bent tng inert eam een ope moder brovaes bare ee ncestors which are O° ; bubbling as the default wa) of even ON quent to target element NORE rower doesa't Brent capturing is t8® Se cue putwerat a re cat code in JavaScit. : Teer oneal pecivly, provide this information. Once an Event function that takes a single ri) method on a node object ethod is as follows: function, usecapture) ype ofthe event ike"ellek oF eter is case-insens vwnen the event oCoUTS fe event Dubbling or event tte ‘opment eriot type="text/Javascripeey Baribweren « windousderieare pucton.addeventlisteneng scr eeteementoyta( ener (el tek TEmy eseris> HE, sayielo, false a (CHANGING ATTRIBUTE VALUES DYNAMICALLY pe racier we ave seen we can change thesttrbute ofan el cpt eon ibute ofan elements at scripting time Java scat Pea eee candy quakntatby igang nen vost hehe rat eae ats of change in atbute value in a user defined function and can call that function when an appropriate event occurs. tance any aeibue value can be reflected fo the wor by Mghhting the vaso et T show the updated value in blue and change the background eolor opin. path many elements (cinput>, <select») of a form object and the change of attribute value code is written has been changed or the cursor is moved ‘the onehange event occurs when the thange in valu of these textboxes the Highligh re hod is called with the name of the element Bample 1: cheal> <head> <titl <script type" function High} > ura, Form </titler oxt/ javascript? ight Evener®) </script> </head> 5 somone purpose ofan option list isto pre Borer terete anna Fisting feces eet te np i | Bowe ame rae ae apean * 10 the ser one a fot fut ‘er wil select the fruits radio TT eae nd when User vl select eee, the {ales dynamia yer at a ection same cs ee ay we an change na the olen fincton by caling wy rupdatelist) function willbe eaten sh en onclick event ofeach radibutton. Bastradiobutvon source, eet ofthe checked radicbuton so that it wl check a ‘aml: a ra head? <tst1e> HIM Form </ettte> <script languages2avascript® typee : Peo "tent/avaserspt"> Function updateList(Elenent¥sive) 4 with (document forms. ay fora) ( 36 (ELenontValue == 3) ‘ optiontist [e]-text = "Mango"; Optiontist (@).value = 25 optiontist [2].text = “Barara"s optiontist [1]-value = 2; ) Lf (Elenentvalues= 2) ( a optiontist [0)-text = “Potstors optiontist (@).value = 1 optiontist (1]-text = *camboee™s optiontist [3].value = 25 ) y </script> ‘/nead> body st1one™ nethod="post”? <form nane="ayform” 3° sone" sizes" > <select mane <option valu <option value=?! </select? voptiontist™ eat M08 nana vam | iment, recs nse) to <form nane="nyforw act a <i cent cx apple"sAppie * values"oran onclick e"eelection()" > Select your favourite Fruits: apple Banana Orange {Pear (5 Grapes | Show You selected: Apple Orange | 1GING LABELS DYNAMICALLY. Ths Ike we have changed an option list dynamically same way we can change a libel of a baton. Fallwteg cepts make se of option st const of rts name) and. buon tially when the est of fruits and label of buttons fruits. Once the use form will be loaded then option list shows t lick onthe button its label will get chan fo the “vegetables” and Ust wil display all the fruits, el Keep changing between fruits and vegetable on Here, button is acting as a toggle button and is ee talc — te) <script language” Function updatel xen (document. forms nrToT) a (Evesen! -erecamiaeae nt javascrit™> ) = Geert tra male nce st tn ma ng Sere frst and an Apesse# rst and lst names The neat ME nthe form iW submitey een ign neal cde wg tet othe ape ce chead tate HTML Fon 8 otsties scoipt Languages Ame from user and using » den fla Function addénait() ‘ with (document. fon . forns.nyform) a (Frare.vatue. length > @ 4 Lrame.value.tength > 8) [Enatl.value = Frane i value. charhe(e)s (name valve + > ? </script> <ineae> body <form nane="nyforn” actione"* methode"post™> First Name: <input types"text™ nanes"Fname®/> <br> Last Name: <input typee"text® nanes"bnane"/><Br> idden" nanes"eratl"/><br> eutton” onsubnit-"adeeaatl()"/> kmail: <input tek Cnput nane="Subnit” value="swonit” 1 </form> ‘footy ‘actions of the Submit scaled ise Javascript has a special set of functios all Button and Reset button of 3 07m, functions that mimic ‘putton and the Reset button with our om Vjaceof these buttons. toreplace the submit en oftetyspayedon form -celele> HOM. Form en ' “form nanan'nytorn™ actlone"" methode"post”> ° ee First None: estotlia if the state is continues to ge object, use the: ‘The possible va ‘element canbe ip Following exar of that user wi + once, user wil content of tex Example: ‘ehtml> “head