You are on page 1of 45
INTRODUCTION TO JAVASCRIPT JAVASCRIPT IN WEB PAGES ‘Today's web sites need to go mach beyond HTML. Ther i «defisite sed slow user, browsing Semen eet eters Tse es ig ‘ses adamily racie e paetn ae mane ge TR Thaw tea te drones evo ha wil sow th eran of Interethe we pge, acer yet for End on he pt mes er ee in content and presentation, to the user. aad Ia he sso ye pth bt tb i om conan eter! inating, MEA 8 tt web ae Cptuing user requests is eaitionally done via a eto ts ena kastonly dove vis + Form. Hence the web ste deepest enroamet ed om UPMEES tip, te frm mse + bit chu fr senda he ination ter requests is generally done via scrip ‘captured back t the web server for procesing | (mal programs) that are based on the terver ovr oe INTRODUCTION To JAVASCRIPT Paes [Addiocally, all development environments provide syetax o erate and use memory varinbles, consti, td fintione If the development envconment is objet oriented it wil provide an object hierarchy to work with. An Objet Oriented Programming (OOF) envitonment always offers event crvenprogeming. This mesa thatthe programming environment will recognize object bared events and allow the connection of code ‘aipptsto these evets, When an event our, the code sippes wil execs All ese ates and more ae availble in JvaScrip, Netscape and JavaScript JInaSerge is a scripting language (web site development environment) crated by Newcape hence SaaSerpe works best withthe Netscape suite of Client and Server produ, ‘The Netscape client browser product is called Netscape Cornmuricator. The defel serpting language that Nevespe Communicator understands is avaSerip. (One Netscape server product, fom it suit of server products, is Neweape Commerce Server. The default sesping language hat Netscape Commerce Server understands i JavaSei. Datebase Connectivity Netscape tas 2 product called Live Wire, which permis server side, InaScrpt code, to connect 10 Relator DataBase Management Systems (RDBMS). RDBMS such as Oracle, MS SQL Server, MySQL, ‘mSQL and a hos of eter widely used relational databases, which generally se ANSI SQL. a thir tra langue. Live Wire database divers aso support» numberof non-reiational databace, Client side JavaScript Cliencside JavaScript is tational embedded into standard HTML program JavaScript is embedded between the HTML tags. These gs are embeded within the . = SIHIEAD> or ... as ofthe HTML program. aaScrp is embedded ino an HTML program because JavaSrit uses the flename il and the HTTP rotor to transport itself fom the webserver othe clients browacr where the JavaSerigt executes and roses lent information. Only » browser that is JavaScript enabled will be able to imerpet JavaScript code. —Netéape [Communicator does his best a JavaScript i he natural language of Neteape Communica Micros Internet Explore lio interprets JavaScript. However, Item Explorer atest relates support nol version of JavaSerit. Hence, he total funetionality ofthe atest reese of IvaScrpt sealable ‘a Neseape Communicators not avaiable in internet Explore. IN ‘map Me cet scr gue of ere plore is VB Sep. Neseape Crm oes at supprt VB Sept Capturing User Input ‘Wb sie interactivity starts fom being able to capture user input. The
. ..
HTML tags can te use wo create a user Requestform. Between these HTML tage the HTML gs can be used fo instantiate HTML objects in the HTML form to filme the cape of wer ua Tew aves ne Tet rgued cnn be bac ‘The place of deliver (address) cannot be lf blank some development ‘he fneonality oF HTML pages already ona web sie nT a8 tly aod Quickly wed to extend The Advantages Of JavaScript * ‘An Interpreted Language: JaveSe This provides an easy deveiopmen interrets HTME ag ge char 08 INTRODUCTION To JAVASCRIPT PAGE 427 [Enbeded Within HTML: JvaSrp doe ot equi ny spacial or spate eof progr tobe wien edited oc compile Kean be wn in any et edt ke Noten, lng with zpptonete HTML Tah ed saved 8 leno ha HTML fee id eobeas ees ee TM intrpied ty ony bowoa at save ule ‘Minimal Syntax ~ Easy to Learn By lain usa few commands and simple rules of syriay, complete ppienons canbe bull using JvaSerip. Quick Development: Because JavaScript doesnot reuite tine consuming compton, serps can be developed in » shor period of time. Tis is enhanced by the Get that many GUI interface fests, such as sles, romps, confinn bones, and ther GUI elements, are handled by ele ide avaSei,the browser tnd HTML code Designed for Simple, Small Programs: It is well suited to implement simple, small programs (or ‘xan, unt conversion caleuletorbenveen miles and kilometers, or pounds ond tlogrant). Sich ‘rograns can be easily writen and executed at an acepable speed using JaaSerp. In addon, they can ‘be eal integrated into a webpage. Performance: nvaSrit canbe writen sch thatthe HTML fils ae fil compact and quite smal, This smiimizes storage equvement on the web server and download ine fort cio. ‘Aaitonlly, because Javacripxprogams ae usually included inthe same fle asthe HTML code or 8 webpage, they require fewer septate network accesses, Procedural Capabilities: Every programming language needs to support files such as Condon shecking, Looping and Branching. JveSerpt provides syntax, which canbe wed to add such proses “apabilties io web page (floname bm! coding Designed for Programming. User Events: InvaScript sopporte ObjecvEvent based programing, JavaScpt recognizes when 4 form Bulton is preseed, The event can have witable JavaSerpt code tached, whi will execute when he Button Pressed event ours. JuvaSeipt can be used to implrent content sensitive help. Whenever an HTML fons Mouse corso "Moves Over a buton or lnk onthe pages helpful and inforative message can be dapaye in testis barat te botom ofthe browser window. Easy Debugging and Testing: Being an ierpced language, seit in JavaScript ar ested line by line, andthe errors are also listed a they ve encountered, a appropriate eror message along with the ine ‘number is listed for every eo tha is encountered. its eny 10 locate ers, make changes, ad et ‘gain without the overhead and dl of compiling ‘Platform Independence / Architecture Nears isa programming language tha is completely independent ofthe hardware on which it works. ICs language that is underdood by any JowSeript enabled browser, Thos, JavaScript applications work on sy machine tat bas en appropiate JavaScript ‘cuabled browser asad This machine canbe anywhere onthe network. Since each browser is for a specific paform, JavaScript ieterpretation wl be with repectt the specific lator. The browser will add whatever platform specific infrmaton i rege othe IaScrgt wil it lterpres the code, Thus, JavaScript is truly platform independent. A JavaScript program developed 093 ‘Unix machine will work perfectly well ona Windows machine. ‘The fc tha platform speife Bowser, msniained a the let end, does the interpretation of lvaSit, relevesthe developer ofthe responsibilty of maintaining multiple sourcecode ies fr mil platform. ' PAGE 120 ‘CWAD USING HTL, JAVASCRIPT, OHTML AND PHP CHAP 08 WRITING JAVASCRIPT INTO HTML, Sino a embed roan HTML Ribot eds HTML fs adie HTML aga. brome nett net be clued a8 an integral pant of an HTML document whe aed a Sea pts informed tat pci scion of HTML cate veep. The home woe busin JavaScript engine to interpre thi cade, mun given his iformacon wing he HTML ings mash endo ener of serpting code (ik mothe HTML tg, he
Outpat For Example ¢: (ert diagram 8.1) DIALOG BOXES JavaSetiptprovides th ably to pickup wer ‘apt r display small amounts of text 1 he ter ty using’ dialog boxer These dialog bones appear as separate windows and thet one depends onthe intormtion provided by the use. This comet is independent of the tat inthe HTML page containing the JevaSaipe seript and does not affect the ‘conten: ofthe page in any vay PRG A ‘OWAD USING HTML, JAVASCRIPT, DHTIML AND PHP (CHAP 08 ‘There are ties typ of log bones provided by JvaScript. ‘The Alort Dialog Box Be et dal to dos he sig pied he rt ts wl sn [SE] buen 1 ss ell asan he Seve ad the HTML prope. in wich tis code pe sed ei nt oe fe ML og in which hs coe pe sl il cenit Tg set dialog box can be wd to dle » carry meme o play tne infest. For 2 Aside te er vb incorecfrmatn een D An invalid result isthe output of x calculation nore ss © Awamig seve on walicons yon dine cram sows an ale lg ot weleoing wer. As son the [SE] ton i licked, niage splayed inthe bonne é 5 ced nga This iets hal background processing taps nn a document writ ", "Deft vee); Example: romper your fvorite color, "Bue" ‘The rave thatthe wer key into the textbox onthe prom dialog box i accepted a can be stored in 8 saci ‘Gxanpie 6.) ‘The blowing example shows a welcoming image onthe scren, Asks the we fora name, Then displays the mime Keyed into te prompt ilo box along with Grestng message. ain ‘cHEAD>Example <ITITLE~UHEAD> <oD¥> “<SCRIPT LANGUAGE="JvaSerpt> ‘document writs cIMG Sre="magenweeome i>", ‘ocument. write *<HI>Greaingr I>", ecument write prompt(Encer Vout Name: "Name"; ‘ocument writ "Rabsp, Welome to My HomePage! I>"), “</SCRIPT> Page a6 ‘OWAD Us HTML; JAVASCRIPT, OHTML AND PHP ‘Output For Example 6 (Referto diagram 8.3) CHAP 09 ‘The Confirm Dialog Box uaSerit provides thin typeof dag bo, called he confi dog box. AS he nae sess, his isos bo serves a techigue fr consrming we action, The confirm dialog box play he olowing 8 [Oe an] ton ‘The confirm dialog box, causes progam exceton thal uni wer ation takes place. User ation can be ‘cto Joon being click orth [ance btor beng clicked. which corte falosiog json ke place. 1 Ghcking on he [GE] bunon causes TRUE to be pasted tothe program which cle the contin alog box 2 Cleking on he [ERRSGT] buon cues FALSE ob ped to he progam which cle te cont log box Display fa conim slog bx thus requires only one block of information: ‘A pre-defined message to be played Syntax: ‘confirm%<Mesage>"), INTRODUCTION TO JAVASCRIPT ait ‘steaD> “TYTLE> Contin Method <TTLE> “SCRIPT LANGUAGE="SanSein'> var quion "What O10? varanser™=2, ‘ar conet=<NG SRC~imapenan i>: varlcit 4MG Seige I ‘at Rejnse = pronpuesin ream enon re) ( tr Wrong Pes OK For Anthea Reso = ponpqeton oma lente Lac Next Time”), PAGE tas “CWO USING HTML, JAVASCRIPT, DTI AND PHP CHAP 06 ‘SELF REVIEW QUESTIONS ‘FILLINTHE BLANKS. ‘Capaing we requests is tionally done vi 8 2. JavaScript sa cing language created by evSctg is embeded between the RTM tgs ‘Aer request form canbe crete withthe HTML tgs, wed to tore vals tat canbe used in other parts ofa rogram. Tre {served for machine generated ode and shoud not be wed in rps. In ease, vibe based on the value tis esgned tot A ‘5x sequence of zero or mare carcters that are enclosed by double (or single () oie 8 block of SvaScrp coe that perform specific ak nd return value. 1, ‘= JavScrp objects hat are capable of strings sequence of values Mh Ag BY isan ary hat has ben created wt each fis clement bing signa specif vie 2 enum collections of atta have properties and may be accessed via methods, 13. The operator calles the remainder by dividing two integers. ‘TRUROR FALSE "4, JavaScripts nota inepreted language 1S. Ader progam dereojed on Unix machine wll ek perfectly wel ona Windows mci 16. The <BODY><CBODY>HTML tags make an ideal place to create SeaScript variables and constns xd 008 17. IumSexipt doesnot allow he data ype of the vail tobe declared when variable i cet, ottaes Charme tobe included in the sing the quote charcer mt be preceded bythe “onttsh () ecepe character 12+ czald panel) and paneon) are te ntins provide by Iver prom eit pe 20. Methods are wed to red or moti the data contained in an object. 2 The combination ofan operator and its operands seed toa expression 22 fa sabe ia doled outside he body ofthe Function its avaable oughou ip inside al function and elsewhere inthe progam. HANDS ON EXERCISES ‘nde codeblock ening ays and generate th curt date in words, his shoul inte ‘te da, te month andthe year. The ouput shouldbe as follows, Saturday, Janusry Of ooac cour oe INTRODUCTION T JAVASCRIPT ace 8 a ia fon’s Text eee. Ie Wie vst cafe ak, whic heck be ott eee in orm o entered is inthe lower case, convert to upper case. Make use of function toUppercase(). 3. Wri Jase code ak wil valet a umn and pened pit ar ended ale eer he nae oc tin fe ot entre ply on eror mesg showing ‘ours ote gud els Pes yon” ; ts cs. els etre oot atch th art coded vee, dpa err esge hong: “Tt ert ald wen pee Ite eds entered match, ply the following message: "Welcome (aerame)” 9. THE JAVASCRIPT DOCUMENT OBJECT MODEL INTRODUCTION Using the Docanet Objet Model (DOM) east enabed bowser det De OM yh collection of web page {fis wt ase lamers) hat ave to be de wth wl rendering on HTML hana eh eee ake TIE epee ret st Sar ore ecw Saihtgreeraaeescenetvamatereate eran Sieh esc aael ato om, Pa The Navigator ~ i. NescpeNevgue, etn is capable of uiucy destin cach element "NED# Aer, Oper, Moni and 00 inthe webpage, because mor elements fa Miadow seteendwebow awh mes TF ocoamene The DOM tint JeSerptrecognies ie decribed in gam. fe JovaSsi's DOM is feed 8a stance herr Instance No HTML cbject is registered ia the DOM” by JavSct cle bow nes thy ae ae in ‘memory por eng edeed te browse win, (Rr ‘CHAP 09 “THE JAVASCRIPT DOCUMENT OBJECT MODEL Paice ‘Whatthis means, i' document doesnot have any Anchors desriba init the Anchors object wil ex but twill be emgy. ihe document does nt have any Links destibod in the Links ject wl ext butt be emp. 2 Hierarchy Below the Window isthe Decument object Below the document objec re ote bjs exis. They ae the Anchor, Link and Form objects. Individual form elements are found under the Form objec. In aditon tothe DON oter objects curently recognized by a JavaScript cabled brows ate Plug-ins, Applets ad Images. Hee sig a avaScript nabled browse ad JavaSipt moa ofthe major webpage ‘objects are accessible, However, every single elamen ofa web page rendered inthe bower window, swt par ofthe DOM, For ecaimple, HTML tags such s <HEAD> ... <HEAD> or <BODY> .. </BODY> are not past of the DOM. Presesation tyes, headings, Baytex, HI to HE and so on are not part of the DOM hence not recoguzed by Jaaserp. Diagn 9.1 shows web page objet that are part of the DOM, JavaScript however, recognizes presentation sve, heading, body text, fH] to HE and 20 0m, when JInvaerpt assed Sie Shes [FSSS] are in a web page. 1355 is usually between the <HEAD> “SHRAD> HTML tagsin a web page. ‘THE JAVASCRIPT ASSISTED STYLE SHEETS DOM [JSSS DOM] 1855 use faaSeipsyetas to contol a documents presentation syle. When a JSSS is embeded in an [HTML page within the <HEAD> ... SHEAD> tag, ten the JevaSerpt DOM picks wp 2 whole new st of objets, which add tothe standard DOM object already recopized by JavaScript. The seal objects bought ito the DOM by 3885 are shown in diagram 9.2. acer ‘By extending the DOM recognized by JavaSeript by embedding ISSS by the nie of ISSS are: n'a veb page, developers of web pags can aces every element of ‘webpage whee this element sppars on he page when ti rendered dent bowser or ot Diy accessing spproprite properis ofthe Navigator object, (Le the ‘Brower, the toprons object nthe DOM, JavaScript can ecogriz the Tower (pe (ie. Newcape Novgeor Internet Explor Opera ‘Moral and 20 on) and subsequently dispatch all ITTML pages othe ‘omer fom the web sever, with a sfle based on this knowledge “This is where the power of JavaScript relly becomes visible i pigrum 9.2: ‘Providing finely tuned web page content to aches browse etaharaapeshaane Since JavaScript understands the DOM and can extend the DOM withthe use of JSSS ina web page SavaScrpt undesands Objet. PAGE-152 (CWAD USING HTML, JAVASCRIPT, DHTML AND PHP HAP 09 Alec tave Propet tat deen te tay of te tet Q Netinds tation sre othe popes ret ha ow JeaSeptcade mips oe crete 0 the bjt by bing mapped to i Appropriate JavaScript event handlers. ad | fs wens ecm ern orca the cafe ie il ec Th te ito Ose, | “Evettven Cos een ode fay oj acl Soran tenn i {) uae ces the mets of al bet belonging othe DOM ad JSSS DOM. Hence i] ins ect tec a {1 Mot sauasees—e |p Deseret acrtmedpoyeenng agape ap eT ort ‘sie jer eed popunting cols Sak Scenes eae , caput iain evs tres are gre ovat vig develope he cpio iy get sep at { _willeeeae in th comet oF web pgs win lease cabled boos cose ee at decd loser |, Although ese drs trove of etre of propane sos roe saute of hj bt tes ht epee Brae ne eg TB tc inde be cain of unter of pref rows an sess ser as ‘esbiyw cone er fase tephra te following charters the focus wil be only on bramser side JavaSriptng. The browse in which Near cae ips wil always run corey will be Neteape Commusiceloe a TriSeap oe ‘Netscape product. JavaScript isthe natural language of Nescape Communicate | UNDERSTANDING OBJECTS IN HTML inc, x at lect, which tongs othe DOM. lvacrip recoprzes «teat box. JevaSerpt Seilatssceess tall the methods of «textbox. One of he methods ofthe lextbox parts noses Set CHAP 08 ‘THE JAVASCRIPT DOCUMENT OBJECT MODEL PAGE 153, ‘Methods Of HTML Objects sn opie deerme te sof a abject. While bing nective web passa ajo’ fepatis nad tw te edn, Le hn hoje tehg wed Toms a oft aed ‘Fovmeing coments an fave fis it gt he van objec popes. Ths lo Fpasces ene tcf ejeat ren un Matis of moet rd oto ge 4 vie of e's prope. Tt demining how Neder Nacht eters nomad Objecane MetndNawe tat Ser pone ea tps bin met nd marie he be’ proper st tun tne Tas pv peat el feat cum woh pgs dele wen ope ve the Seve o ean. Cnc rip code scp set sid np! nr eds cles rower pram on dead web tegen be sce an seta he browser om we seve. BROWSER OBJECTS cosh trove: ods nb pag, the bowel eee sunbe of Jima oj tm rapt DOM or 5S BON) tt DOM, wich proves nase cote obec tat elements £0) SS ee ee leind Sea SEG Ae alae be vn votes WO pope al taxed contents ofthe ext box. Hene, JavaScript can proces the contents of ny textbox inte HTM ae Properties Of HTML Objects, est ke real word objects, HTML objets have «numberof propertes that determine the beluvior of that ‘object. An object's properties can be referenced a. ObjectNamePropertyName Focexample a textorcan have propets i name sce and 0 on, ( i objet 10 [To access the document cre Toaded ito a window. Te document objet [decment__ |i TA. document tht provide content, hats one that as HEAD end BODY Fo represent « URL. Ik cn be used to create x URL objec, acess pats of « URL, ection | ody an existing URL. [sary [To matin a history of he URL's aoced wiina window Hessen fermion set oxen ofan ext el 5 a [To access information about the size end color depth of « client computer's sereen [cris cea bower rag coo GWAD USING HTL, JAVASCRIPT, DHTML ANO PHP ‘CHAP op 1D Apples D Mulkiesi objects sucha audio . GA Fen with various form mae ame Ve les The bower cents, : HTMLojecs 2 AUAUStATEmery oer HTML aie inthe docunent, hus regisrng echo tise ject we ‘amen, whic wl oie w he cater says wl od indexed [SLL ba wilbeenpy hem cena iy” eM TML he tw eat pei object Properties can be set wing JaveSeript. Thar the fintionality ofan HTML object can be controlled while the HTML page is raming in ‘THE JAVASCRIPT DOCUMENT OBJECT MODEL say alte below: [Te acess the tet of hyperliok. The chess neray STS EST snchor objets within a document ro Acces ava apple." The apples array Bola Wad vo aes a ep ina document [To secess an embedded object The embed array proves acces al lerbeddes objet ina document [Te access information abou particdar MIME iypenapponed bya Wows Ta] jmitnTypes array is an aray ofall the mimeType objets sepponed by | To assess ifetiaion about a parcuar Browser plain. The plugins array 5] rowser onary of l plugin appr bya [Form Forme anay {1086088 an HIM orm. Th forms array i ued cis oar Win "Taio 92 (Coninaedy Jeet form elements amy [cste by Nets: Communica: felemens [Acces tall the form element in the form. fet [To aces text eid of form. [estar [Toaces text ates of form. Fo access set of rio Butons onthe Tm ft acest an Fail aio Won wi [checkbox [To acsear a cestbox ona foam [baton [To acces form burton thai oes o en ato [submit — [To acs ub Buon on fon. [opin [To aces reset buon 0 a form. acces let it of fom. [Te opin objects used to aceon the ence [To access pasword felon form. FToasees« hdien object ona form. cd [seupead [To aces le upload element of orm ~ Tabled ‘THE WEB PAGE HTML OBJECT HIERARCHY ‘This a Insonce hierarchy. Tis means ia web page does ot have a specifi HTML obj ein in itthearay ascites with that specific HTML objet wil ers, bu wil hive no elements ‘Access To Elements OF A Web Page ‘Concepaally once a web page is rendered (panied) ina browser window i is completely static. Fox any program cds to be able to interact with the web age, each elemest of he webpage would have to ‘beheld im memory, with unique name. The unique name tants toa cone are it emery where the web page element resis, Hence, while» web page is being asembiedin memory (RAM) pric being emdred (made vill) in the browse’s window, a JavaScript enabled browser erates several arys as describe eer. These ays bol efiences to inlvdan webpage abject in thi indeed) element, ‘epation oprocesing of any web page element i done, based on client Is then an ign rs done, gate we page then How A Web Page Element Is Manipulated $HTML ng ae we crt obec ins we ae Fo ean INPUT TypeTEXT> ‘wilinstanates textbox onthe webpage when ncomered HTML cote oT ch HIM hj inane na wb page as properties od methods tht slow eet thoes opis. ach HTL jt hs on eet ee ras an oe hee ‘raed, Tht en HTML oj on ncogian sei ena she hce (nc he HTML be copie hat on vena ce knowledge aa be psd wo ear saat ae rnp On er To can neg one woe sand Jeep ‘vet Hodes The mnt ofthe Det ea ae eee ee HTML object's event name. besos a & ee ee oe serait provides an event Sn ctledonChange ht itera bound the Change vet fe tit bore Choa Se fe text box tas 0 the Change cent hander of Sree The wang nee ea JuvaSciptcnthen execu opposer cate maps Foro “INPUT Type TEXT eens ry Fun on) He the JS fonction myFuncton is bound the JenScrpt eet td enh ‘sssignment operator (=) does this binding. a — ‘Ths Peer onChange event handle, bound whe HTML objet TEXT by being passed aoe ot Hence, os soon as event of a Hane the Change event of he textbox oocus the JvaSeriptevet hander onhange is ‘Since de JeaScrp function myFunctin is bound othe JavaScript evet handler onChange, a oon at ‘he onChange event handlers invoked the JnvaSaript code in my Function execoes, HANDLING (WEB PAGE) EVENTS USING JAVASCRIPT. ‘veh eu even old be nected withthe acon fe mes cana te web pge Such DA mouse-click on an object in a web page rae: Thenovenen othe mou car asa we page Teco arorhoveng tsps pa ene page an en Tes wile ven rege he Wako cet af BC OOM. ‘iter webpage eves could be the opening or clsng of Window, the loading ofan image inane page CHAP 09 “THE JAVASCRIPT DOCUMENT OBJECT MODEL ROE >> 3raSerp's approach to Working with web page elements it aml step proces: Deity a eb page object. ‘Choose an appropriate even asociaed with the object "ive a stand method of connecting an objets event and JavaScript code snippets JavaScript event handlers mapped oan obec’ events do this, vate has several named event handlers hat ae mapped oan HTML objets events. To work wih Davari its necessary to understand ow to use JavaScript Event Handler’ cory. Javascript event handlers, canbe divided into vo types Fnteractve ad Non Interactive ‘An interactive ever lander depends on user interaction with an HTML page Fr example the JvaSeript ‘onMowseOver event handler sam interactive event handler This egies the ur to move the mouse camer vert web page. A JansScrip,no-oteractive, event handler, doesnot need user itration to be invoke. For example the JavaScript ‘onLoad’ event Randle is non-interactive event handler as automatically executes whenever ‘Teen oaded into webpage, ‘Table 94 dts JavaScript event hadlers tht descriptively bound a HTML objet events. As long athe ‘HTML objet has an associated event, JavaScript provides a eeocited, named, event andl. [Named JavaScript Event Handlers javaSerpt Kent Handler | Wil Be Caled When fonasert Toading of an image abo ak real of we action oo cr [A dorument window, fae set orm cre! es caret pa IA ext el, ext re, fiploded field or elton i edie ad Toss = he cuenta ati An, centsie ge ap ko doconen ied seach [Rink lente reo doce soul TEED [entragDeen [A dragged objet dapped na window Fe [onfor [Anerrr occurs ding oading ofan image, window or fame TA document, window, frameset, or frm element resives the caren pa onFecat [oakeyDown he use presen Key fookayPress [he use presses and relies Key [okey be use eletes Key onkead [An image, document or Fame ei Tonded (onMousDonm he use presses a mouse button [nNbuveMove he user moves te rouse [onkuseOut he mouse i moved out oF ink or an are oa clon ide age map (onMouseOver The mouse i moved over fink or an sta of lent side image map onMuseUp [The user eases « mouse bution oofesee [The user eset a frm by eliekng on he forms est bation onfesiae he une reais window or fate lonSdee. [Texts selected in text Geld or a textarea oassbm [The user prese ors submit baton (onUsond [The user exis document fame Table 4 PAGE 188 ‘GWAD USING HTML, JAVASCRIPT, HTML AND PA ‘cHAaP 09 ‘Tbe paring convention followed by Sava Sript makes it eaxy to identify JavaScript vert handler, The SaaS, event fondle’ name, ‘ ‘nMfoaseOvr ‘A Heft sstindia.com onMouseOver="<JaaSerpt code snippet itself» or <A call o @ JanSsipfinclon>">Text associated with the LinkJA® ‘Het, he onMonseOver Jean event hander i bound fo te ypedine > a HT, tag, When the moube cuaor moves over the hype it MouscOver eveal soca, Whee It ieaScit code snippet i dry pased as «vale wo an HTML nabte gad b eclned dsl amis"), then double quotes (") cant be used within he eonal tase eee Repaing tee dacble ques with single quotes () whee necenay ‘To mse the JenSctipt DOM and manipulate is Bere propio wll help in eising this base ‘amit lel to conience level equi fer caing a Ieascpe To achieve this evra examples which wie the HTML <FORM>-... <IRORM> as along with thirst maped to avait nde wl be sed ‘SELF REVIEW QUESTIONS LLIN THE BLANKS Using the JavaScript enabled browser identify the collection of eb page abject at have Jo Be deal with Wile rendering an HTML based web poe te Goon window ees tse IaaScript control «documents presentation syle fm object are sed ost or ges value of en object’ propery. JavaScript event handlers can be divided into two types nd, best is weed to access information about the browser tht is executing the coment * a a 5 scape ‘TRUE OR FALSE the document doesnt have any inks described in i the Link objec doesnot ens. 1. Invert ‘onLoad” event handler it an interactive event handler os it sstomsially excves whenever a fom is loaded lata webpage {The browser cents one ary in memory pr HTML objet in the document. CHAP 08 ‘THE JAVASCRIPT DOCUMENT OBJECT MODEL, PAGE 459 HANDS ON EXERCISES 1 cute « (oie fi, wih aie bets oe aes the moe pote sores rhe ge Un SowsOv a eaounOt ee aes. Te oape es ‘fowaintedagans 9 wd 3 Dusgram 5: Out for ads on Exeeue. Diagram Dr Out Hanes on reese 10. FORMS USED BY A WEB SITE ‘An ML am provides dt ptr fctomlty to eb pge, Th is very ee he web se is ein ave od vel rode, HTML foe prove «fl ge oF GUT ee a IML frm can stonmtaly bat te coleced a conten oe z ‘The ata ited cn be proceed athe eb server by Ct sso 7 Gt programs, ever side aves, va Jui alow win of ct i a he ti seep nb ‘mer that ony valid dats is returned to a web server fr further processing, if ae ‘Tadtcealy esr input is captured in 2 Form. HTML provides the <FORM .. > tags wit which ae HTML form canbe created 0 cope user ap per oma ITM eis ed hee he <FORM <FORM gt ae Tet, Tethren, Rade Seton, Baton, Chek Beads om. An IML fon end een tne age cited ure rad ang eed Lan Nee Sezee cvaned icf) een Oe teach ope ee ‘45 1 control the functionality of the form at ran time, pene! is CHAP 10 FORKS USED BY AWER site ‘Ther are two forms inthe HTML il; Formt and Form. Refer dngam 101: These will be held inthe fist two element ofthe Forms anay. Formal willbe an adress, which points to where the Form elements aay is located. Form in the Forms acay, wil bea reference t the content aca whe the elements of Form! ae located. Form! has thee frm cements Foon? inthe Forms ary, is reterence to the context erea where [2 the element of Frm ar lested. Form bas ie form clement ‘To understand this model, let us write JvaScrpt procedure that willed the elements ofthe Form object's ary, and fet the ‘mumber of acl form objects held (Onc the reference tothe form's elements are known let us write §aaSecpt procedure tat will read the each Forms Elemest aay nd vetunthe nares of the form elerens held in the ay. The lemints hed in each ofthe arays must be excl he same athe lemens desecibed tetween the <FORM>..TFORM> taps in the HTWL file rnning inthe browse, the elements aray match the muber of demens deserted between the “<FOEM>~<FORMD gs in the HTML age act, The ciagram 102.1 shows an Alert box that <dspays a message indicating the numberof form elements of implemented by the Fit Fomin the HTML fle. Relectothe HTML sand JiaSerot ode described in Exercise | Pop up an Alert tht daplay te inva form elements of the anay and recognize Ihot these ace the same as are specified between the <FORM>..<IFORMD igs the HTML program | ‘The singram 10.22 shows an Alert box spying” message at the Textbox named Text ofthe First Form ie at position inte Elements ary. Diagram 102 valve’ ad [i [Foes -elenen dex [Value [Porm slenese fore slenente 2.2 Second message for Breas I. 2 —[froena- element i Ford loner Diagram "The Form cae | MS C0) AGeCGE ‘the! Form Sheard eet: BAL eRe function Veron) ( = form alementength; (for lemens name = “Buon { Sle Fiest form name :"+ document foms0]oame), ‘erNo. of Form clement of "+ document. fora{ name + ‘ei (en amet) = Bato | sketSrnd enna doc aaa 1 eta fFomenenso dace ae m4 yy ord; i H) ‘ler(frm.slementijname + ; <SCRIPT <nIEAD> <Booy> <FORM Form 1 FIRST FORM: <><B>Survey Form | <I8></P-<ER><BRI> ‘Et Name <INPUT Name="Texl" Type~"Tent™ Valoe=™ D<BR/><ORD> “<INPUT Name"Ratiol” Type="Radi’ Valu" > Prohe, SREUT Namew"Radio2” Type~"Radio Valuo-™ > Experenced<BRU>-<BR> ORNL Neme= Baton" oatick="Var em) Type-"Buten” Vober “<FORM Namew*Survey Form 2°> ‘SECOND FORM: <P><B> Name: positon + usr 2 itusates te we of orm objec’ Elements aay Focus: The state of « Radio bution and a Checkbox on the ™ Diagram 1-31; Fst mesge for Exercue ‘Oncticking he int Al's [BHT] aton, note Alert pops up ta splaysa message indent the Radio ttn i checked, when te same ‘Set Element Aray Vali’ bun was cick. ‘Concepualy,wihou clicking on the HTML form obo their “Checked properties have been se. Thi tsa how JavaScxpt code can aces fons lament via the form elements ty ad maple ‘lment pope. ‘As soo ashe element propries shane the Browser wil dipay the oject wih changed property in fee HTML page in faenine2 Diagram 10332: Send message fr Eres ‘The Code Listing For Faerie 2: ler("The Radio buon ju gt checked"), ) <SCRIPP><nHEAD> <BODY><FORM> (Clint Name : INPUT Namew"Text TypewText Vales" <BR><BR> (lint Ades: <INPUT Name="Tent” Type="Tex" Value="" > <BR><BR> ‘Cent E-mail Adress <INPUT Name~"Text2" Type~"Text” Value" ><BRO-<BR> <INPUT Name="Radi Type="radio" Vlue=" > Male <INPUT Name="Radio" Type="‘ado" Vale="" > Female<BR><BU> <INPUT Nare="Chect” Type="ChechBox Vales > Employed <BR><BR <INPUT Narvs"Br on ick: “Chthisform)" Type "Batn™ Valuce"Set Hemeat Ary Va” <rFORM>-<BODY> <tt> The dagam 1044 stows on ji Faceted stow a Ait box tt dps « message ideing atte Ades sd the Mast” 1242 sown an Alert box tht dsplys a menage indicating hat al he Textoxes have hems message or Eerie 3. evan sone brn es can be ipleneted nay HTML fom sing Inept ‘Thus dat being entered into an HTML form can be spate to a web server fo furber rocessng. Tae) rn "SEAD-SCRIPTLANOUAGEMAVASCuS a ae Sisietiea Wm fae ero ae 1 seit (G> 3.6&—D) ( ‘ler Textbxes are fille in- ThankYou alate onthe clients machine before being it locumen. orm} ements. vlue =~) ( ler Please fila the following Textbox! Textboxes ="); ocumnent.forms(0) elements fous) beaks ; i ) ) ‘¢SCRIPT><IMEAD> <BODY><FORM> Fes Name : <INPUT Names" Fitname” Typeset” Sie~20 >> Last Name: <INPUT Name="Lastame” Type="Tet”Sie=20 “<P Adress: <INPUT Narn" Address" Typer"Tent” Sae-80 ><> “P>Pincode : <INPUT Nare="Pincode"Type="Text Size-6 ><> <INPUT Names" onClick" vei)” Type="barton”Vale= Ver > <FORM><BODY> ‘The Form Object’s Methods HITVL forms can be made up ofa varity of HTML clement that accept aser int. The <FORM </FORM> HTML tags enclose the HTML elements that make up the form. Once lvaScript enabled ‘owner encounters these tags in an HTML fle the JavaScript enabled broveer crete «form sbjet in ‘memory, which i held a an element ofthe forme ray. ‘The form object has properics lite Name, Mettod sd Acton. Method ‘The Method property ofa form is used o specify the method used to send data captred by varios form lements bck to the web server. The method ued canbe eter Geto Pet. ‘The Get method sends the data cxpared by form elements tothe webserver encoded into « URL, which points toa we server. The da apted inform elements ie appended ote URL- “This technique is used when there isa small amount of data being sem back tothe web seve. The ‘maximum amount of ta that can be setback othe we server xing this method s 1024 bytes ‘The Port method sends the dat xpared by form elements back to the webserver ab & separ bittream ‘of ua. When there i large amount of data tbe setback othe wa eerver, this isthe method wed. ‘tne method atibute i ot specified within the €EORM> <IFORM> tgs the defoult method wed by the ‘rower to seed data bac othe web servers he Get method, Les an encoded URC. ‘Action ‘The Acton atrbute of he <FORM>..</FORM> tgs point othe URL (edérst of « progr onthe ‘we seve that wil process the form data eared and being seat back The server sde program that Process this dat canbe writen nay siping language tat he web eer understands. has been left empty, popup an Alert indicating which Textbox has been left empty. When the Alert's OK aes is clicked on, Set focus to that specific Textbox. [fall the Textboxes are filled, le The diagram 10.4.1 shows an Alert is indicati Mg ei box that displays 2 message indicating that the Address and the ‘The diagram 10. indicati filled," 104? shows an Alert box that displays « message indicating that all the Textboxes have been 10.4.1: First message for Exercise 1- This is asi ich i i na ra Simple exercise, which illustrates how JavaScript code can be used to validate data that is entered Based on this concept, business rules can be implemented in any HTML form usir Thus data being entered into an HTML form can be validated on the ene dispatched to a web server for further processing, the cx a fae ‘The code listing for cersie ) <HTML> <HEAD><SCRIPT LANGUAGE="JAVASCRIPT"> function verifyData() { 20; em; for (i=0; icmds i++) { if (Gocumeot forms(0 elements value =" el; r=r+""4+ document.forms{0].elements[iJ.name + } elseif (i> 3)&&(a==0)) { ~ ; alert("All Textboxes are filled in- Thank You | A PAGE 46s - CHAP 10 FORMS USED BY A WEB SITE for (i=0; i<=45 i++) { if (document.forms{0].clements{i] value =") { alert("Please fil in the following Textbox / Textboxes :-" + 1); document.forms{0}.clements[i].focus( }; break; } } <ISCRIPT></HEAD> <BODY><FORM> First Name : <INPUT Name="Fitstname" Type="Text” Size=20 /> Last Name : <INPUT Name="Lastname" Type="Text" Size=20 /> ‘<P>Address : <INPUT Name="Address" Type~"Tent” Size=60 /></P> <P>Pincode : <INPUT Name="Pincode" Type="Text" Size=6 /></P> <INPUT Name="act" onClick="verifyData{ )" Type="button"Value=" Verify" /> </FORM></BODY> <SCRIPT Language="JavaScript"> document.forms{ 0] Firstname.focus( ); </SCRIPT> </HTML> The Form Object’s Methods HTML forms can be made up of a variety of HTML elements that accept user input. The <FORM> </FORM> HTML tags enclose the HTML elements that make up the form. Once a JavaScript enabled ‘browser encounters these tags in an HTML file the JavaScript enabled browser creates a form object in memory, which is held as an element of the forms array. The form object has properties like Name, Method and Action. Method ‘The Methad property of a form is used to specify the method used to send data captured by various form elements back to the web server. The method used can be either Get or Post. The Get method sends the data captured by form elements to the web server encoded into a URL, which points to a web server. The data captured in form elements is appended to the URL. ‘This technique is used when there is a small amount of data being sent back to the web server. The ‘maximum.amount of data that can be sent back to the web server using this method is 1024 bytes. ‘The Post method sends the data captured by form elements back to the web server as a separate bit-stream of data. When there is a large amount of data to be sent back to the web server, this is the method used. Ifthe method attribute is not specified within the <FORM> </FORM> tags, the default method used by the ‘browser to send data back to the web server is the Gef method, i.e. as an encoded URL. Action ‘The Action attribute of the <FORM>...</FORM> tags points to the URL (address) of a program on the web server that will process the form data captured and being sent back. The server side program that processes this data can be written in any scripting language that the web server understands. PAGE 168 CWAD USING HTML, JAVASCRIPT, DHTML AND PHP. CHAP 10 The Text Element Text elements are data entry fields used in HTML forms, Text fields accept a single line of text entry, Properties The text object has the following properties: O name OQ value Methods The text object has the following methods: 2 focus 2 blur, Q select() (Selects the text in the data entry field, i.e. causes the text to be highlighted), Events Q Focus() 2 Blur) GQ Select() O Change() JavaScript provides the following event handlers for the text object's events: Q onFocus() onChange() Syntax: ‘INPUT Name="<NameOfTheobject>" Type="Text" Example: <INPUT Name="txt_age" Type="Text" Value="18"> This places a Text field (ie, a single line text edit area) within an HTML form, which can be referenced by the name txt_age. The textfield will immediately display the value 18. The Password Element Value="<Defaultvalue>"> ‘The password element is a unique type of text entry field. All keystrokes for this field are displayed as an asterisk [*]. This makes the password element ideal for accepting input of confidential information, such as ® password, bank account number or a personal identification number. 1S The password object has the following properties: defaultValue Q name O value CHAP 40 FORMS USED BY A WEB SITE. ‘The password object has the following methods: a focus() a blur() _ Gece text in the password element; ie. causes selected text to be highlighted), Events : The password object has the following methods: a Focus() a Blur) @ Select() 2 Change() JavaScript provides the following event handlers for the password object's events: Q onFocus() ‘ 2 onBlur) 1D onSelect() Q onChange() SeSNPUT Name="<NameOfTheObject >" Type="Password" Value="<DefaultValue>"> es 2 eNPUT ‘Name="txt_usr_pswd" Type="Password” Value=""> This places a Password field within an HTML form, which can be referenced by the name txt_user_name, The Button Element : eA ‘An HTML button element is a commonly used form object. It is generally used to trigger appropriate level processing. Properties QO name 0 value Method Q click() Event | O click() JavaScript provides the following event handler for the button object's event: Q onClick(). Meee Name="<NameOfTheObject>" Type="Button" Value="<ButtonLabel>"> Example: aces, son “INPUT Name="bin_check" Type="Button" Value="Veri PAGE 170 CWAD, USING HTML; JAVASCRIPT, DHTML AND PHP CHAP 10 fi [Tis Plates @ Button on the HTML form named btn_eheck. The button will display the text Verify... on its face as a label. § Exercise 4: Focus: Develop a HTML Page, which accepts; QO Any mathematical expression Q Evaluates the expression G Displays the result of the evaluation To achieve this a form is created which has two ‘Text objects and one Button object as shown in diagram 10.5. The first Text object is used to ‘accept a mathematical expression for evaluation, When the Button object ( ) is clicked on, the second Text object will display the output of the evaluation of the expression entered into the first Text object. Refer to the HTML and JavaScript code described in Exercise 4, ‘The Code listing for Exercise 4: <HTML> <SHEAD><TITLE>Using Text and Bution objects in an HTML Form .

Welcome to the World Fi McDonalds ' ec roe

Select the Menu Items of your choice - < "D>Major dishes :
pre et " MULTIPLE: onBlur="pick(this.form)"> /alue="Mc Burger->80" SELECTED> Mc Burger Fish Filles Chicken Burger > Starters :
OPTION Value=" ">'Check these out’