http://docs.jquery.

com/Tutorials:Getting_Started_with_jQuery

Tutorials:Getting Started with jQuery
Setup
To start, we need a copy of the jQuery li rary, which we can get from the main download page. The jQuery Starter!it pro"ides some mar!up and #SS to wor! with. $fter downloading and e%tracting its content we put jquery.js into the same directory and open starter!it.html and custom.js with our fa"orite editor and starter!it.html with a rowser. &ow we ha"e e"erything to start with the notorious '(ello world' e%ample.

Hello jQuery
)e start with an empty html page:
<html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> // we will add our javascript code here </script> </head> <body> <!-- we will add our H !" co#te#t here --> </body> </html>

This page just loads the jquery.js li rary *ma!e sure the +,- points to where you stored your copy of jquery. This e%ample assumes that you store it in the same directory as this e%ample file/. Two comments indicate where we will e%pand this template with code. $s almost e"erything we do when using jQuery reads or manipulates the document o ject model *012/, we need to ma!e sure that we start adding e"ents etc. as soon as the 012 is ready. To do this, we register a ready e"ent for the document.
$%docume#t&.ready%'u#ctio#%& ( // do stu'' whe# )*! is ready +&,

3utting an alert into that function does not ma!e much sense, as an alert does not require the 012 to e loaded. So lets try something a little more sophisticated: Show an alert when clic!ing a lin!. $dd the following to the <body>:
<a hre'="">"i#-</a>

45678989:.doc / 5

To get started. +&.&ow update the $(document). 45678989:.ready%'u#ctio#%& ( $%"a"&. This should show the alert as soon as you clic! on the lin!. . -ets ha"e a loo! at what we are doing: $("a") is a jQuery selector. +&.t inds a clic! e"ent to all selected elements *in this case. To try some of these selectors.doc / 4 . The click() function we call ne%t is a method of the jQuery o ject. This is similar to the following code: <a hre'="" o#clic-="alert%. The list has an .clic-%'u#ctio#%& ( alert%"Hello world!"&.0 'orderedlist'. therefore $() constructs a new jQuery o ject. >oth approaches can e com ined.getElementById("orderedlist"). The first uses a com ination of #SS and @3ath selectors passed as a string to the jQuery constructor *eg. we e%plore selectors and e"ents a little further.ready%'u#ctio#%& ( $%"/orderedlist"&.add0lass%"red"&. )ith this in mind. $("div > ul a")/. . +&. you could select it y using document. )ith jQuery. $ itself is an alias for the jQuery 'class'. just as we separate structure and presentation y using #SS. we select and modify the first ordered list in our starter!it. it selects all a elements.ready handler: $%docume#t&. The second uses se"eral methods of the jQuery o ject.&">"i#-</a> The difference is quite o "ious: )e don<t need to write an onclic! for e"ery single element. Interesting links for this section: • • • jQuery >ase jQuery ?%pressions jQuery >asic ?"ents Find me: Using selectors and events jQuery pro"ides two approaches to select elements.n classic =a"aScript. a single anchor element/ and e%ecutes the pro"ided function when the e"ent occurs. )e ha"e a clean separation of structure *(T2-/ and eha"ior *=S/.Hello world. in this case. we do it li!e this: $%docume#t&. we want to select the list itself.

find("li") is mostly the same as $("#orderedlist li").remove0lass%"2ree#"&. )ith those selectors and e"ents you can already do a lot of things. 45678989:.doc / C .'i#d%"li"&. +&. Some other e"ents. Bou can find a complete list of all e"ents in the jQuery ?"ents 0ocumentation. &ow lets add some more classes to the child elements of this list. $%docume#t&. onsu mit. Therefore.hover%'u#ctio#%& ( $%this&.each%'u#ctio#%i& ( $%this&. li!e ready and ho"er. when you reload the page in your rowser. $%docume#t&. ("#orderedlist").add0lass%"blue"&. li!e onclic!. ut only on the last element in the list. find() allows you to further search the descendants of the already selected elements. There are many other selectors similar to #SS and @3ath synta%. ut there is more. +3'u#ctio#%&( $%this&. onchange. This selects all child lis of the element with the id orderedlist and adds the class ' lue'. +&. a""end() is used to append some te%t to it and set it as te%t to the end of each element. +&. there is a jQuery equi"alent.add0lass%"2ree#"&.The starter!it pro"ides a stylesheet with a class 'red' that simply adds a red ac!ground. . Aor e"ery on%%% e"ent a"aila le. 2ore e%amples and a list of all a"aila le e%pressions can e found here. use themsel"es. $%docume#t&. li!e add!lass().appe#d% " 45!! " 6 i &. you should see that the first ordered list has a red ac!ground. $nother tas! you often face is to call methods on 012 elements that are not co"ered y jQuery.ready%'u#ctio#%& ( $%"/orderedlist li1last"&. The second list is not modified. are pro"ided as con"enient methods for certain tas!s. +&.n this e%ample. &ow for something a little more sophisticated: )e want to add and remo"e the class when the user ho"ers the li element.ready%'u#ctio#%& ( $%"/orderedlist > li"&.ready%'u#ctio#%& ( $%"/orderedlist"&. Thin! of a form you would li!e to reset after you su mitted it successfully "ia $=$@. 2ost methods. eac () eac () therefore $ iterates o"er e"ery element and allows further processing. +&.

+&. The #e$"ression% synta% is ta!en from @3ath and can e used to filter y attri utes.doc / F . iterate o"er them and call reset() for each. Therefore all li elements get a order.reset%&.css%"border"3 ":px solid blac-"&.ready%'u#ctio#%& ( $%"li"&. $%docume#t&. Thin! of an unordered list where you want to select all li elements that ha"e no ul children. a"aila le in any "ersions after 5.$%docume#t&. )hile filter() reduces the selection to the elements that fit the filter e%pression. not() does the contrary and remo"es all elements that fit the e%pression.n case you had more than one form.reset%&. jQuery pro"ides filter() and not() for this.5. This would select all forms within your document. t is refers to the actual element. +&. This can e a pro lem as rowsers eha"e quite inconsistently when returning what they thin! the 'href' "alue is *&ote: This pro lem was fi%ed recently in jQuery.reset() to reset all the forms on the page. since the reset() function elongs to the form element and not to the jQuery o ject. +&.ready%'u#ctio#%& ( $%"a7#ame9"&. 2ore often than selecting anchors y name.eac () function. This code selects the first form element and calls reset() on it.each%'u#ctio#%& ( this. +&.clic-%'u#ctio#%& ( $%"'orm"&789. &ote that in an . $lso note that. e%cept the one that has a child ul. $n additional challenge is to select only certain elements from a group of similar or identical ones. +&. This selects all li elements that ha"e a ul element as a child and remo"es all elements from the selection. we cannot simply call $ ("form").ready%'u#ctio#%& ( // use this to reset several 'orms at o#ce $%"/reset"&. 2ay e you want to select all anchors that ha"e a name attri ute: $%docume#t&.#ot%"1has%ul&"&. +&. . This adds a ac!ground color to all anchor elements with a name attri ute.ready%'u#ctio#%& ( // use this to reset a si#2le 'orm $%"/reset"&. +&.css%"bac-2rou#d"3 "/eee" &.5/. To match only a part of the "alue. you might need to select anchors y their 'href' attri ute. you could also do this: $%docume#t&.clic-%'u#ctio#%& ( $%"'orm"&. we can use the contains select 'DE' instead of an equals *'E'/: 45678989:.

+3'u#ctio#%&( $%this&. Thin! of a A$Q page. +&.n addition to si lings. (ere we use some chaining to reduce the code siGe and gain etter performance. all selectors were used to select children or filter the current selection.slide o22le%&. the parent paragraph is searched and a class 'highlight' added and remo"ed.hide%&. +&. The jQuery code for this: $%docume#t&.doc / 7 .#ext%&. >y using end().clic-%'u#ctio#%& ( $%this&.dd. +ntil now. you can also select parent elements *also !nown as ancestors for those more familiar with @3ath/. There are situations where you need to select the pre"ious or ne%t elements. instead of the dd children. +&.add0lass%"hi2hli2ht"&.'i#d%. -ets go one step ac! efore continuing: jQuery is a lot a out ma!ing code shorter and therefore easier to read and maintain. The following is a shortcut for the I*document/. +&. we use I*this/.pare#ts%"p"&. when the question is clic!ed.'i#d%.clic-%'u#ctio#%& ( // do somethi#2 with all li#-s that poi#t somewhere to /co#te#t/2allery +&.ready%'u#ctio#%&( $%"a"&.pare#ts%"p"&. so we can start search with the ne%t find() at our Hfaq element. 2ay e you want to highlight the paragraph that is the parent of the lin! the user ho"ers. . )ithin the clic! handler. the first find() is undone. This allows us to quic!ly select the answer following the clic!ed question.&. Try this: $%docume#t&. 45678989:. +&. where all answers are hidden first.&.ready%'u#ctio#%& ( $%./'aq.remove0lass%"hi2hli2ht"&.=/co#te#t/2allery9"&. as <Hfaq< is only selected once.ready*call ac!/ notation: $%'u#ctio#%& ( // code to execute whe# the )*! is ready +&. Aor all ho"ered anchor elements. !nown as si lings.e#d%&. and shown.&.ready%'u#ctio#%& ( $%"a7hre'.hover%'u#ctio#%&( $%this&.dt. the function passed to the click() method.ne%t*/ to find the ne%t si ling starting from the current dt.$%docume#t&.

+&.clic-%'u#ctio#%& ( alert%"Hello world!"&. documentation Jisual jQuery K $ categoriGed rowsa le $3. Interesting links for this chapter: • • • • • jQuery $3.doc / 9 . jQuery Selectors jQuery ?"ents jQuery 012 Tra"ersing 45678989:. e%ample. starting with $=$@. we want to e%plore some other aspects.$pplied to the (ello world. documentation. with the asics at hand. +&. we end with this: $%'u#ctio#%& ( $%"a"&. &ow.

with a class of <foo<. ./egister.f you already !now #SS *which most we de"elopers do/ then you<re going to e fine.)%")' Get the input field<s "alue with the name of < ar<: $("in"ut#&name0bar%").s o+()' (ide all di"s that are currently showing: $("div(visible").foo#a%")' Get list item that contains lin! with '. ut we thin! that de"elopers will really appreciate the ad"antages of each language.valid too( $("ul > li") -. these articles in the ?nglish )i!ipedia may help clarify a lot: @3ath and L Using CSS and XPath Together This is a point of confusion. plus some custom code to glue it together. that ha"e a lin! in them: $("". the est parts from oth of these query languages were ta!en. ?ssentially.f you are unsure a out the general differences etween the techniques discussed here..val()' $ll chec!ed radio uttons: $("in"ut#&ty"e0radio%#&c ecked%") .API/1 1 !/"#$/Tra%ersing/Selectors jQuery selectors are a com ination of #SS 5KC. ide()' Show the first paragraph on the page: $(""(e)(*)"). and used to create the final jQuery e%pression language. @3ath. ide()' Get all list items that are children of an unordered list: $("ul. (ere are some e%amples: (ide all 3aragraph elements that contain a class attri ute: $(""#&class%"). please feel free to post to the mailing list.f you still ha"e questions concerning how this selector language wor!s. . Get all 3aragraphs. com ined. for some: (ow can you use #SS and @3ath together.li") .egister' te%t inside: $("li#a(contains(. jQuery ma!es some allowances to ma!e this happen. 45678989:.doc / 8 . they<re so different.

0 equal to 'myid'.ar5 an ? element whose 'foo' attri ute "alue is e%actly equal to ' ar' '43foo76. an A element child of an ? element ' 0 . and G elements Supported.ar543.op5 an ? element whose 'foo' attri ute "alue is e%actly equal to ' ar' and whose ' aG' attri ute is e%actly equal to ' op' 45678989:./ ':not)s* an ? element that does not match simple selector s ' .led a user interface element ? which is disa led ':checked a user interface element ? which is chec!ed *for instance a radioK utton or chec! o%/ ':selected a user interface element ? which is selected *one or more option elements inside a select/ K not in the #SS spec. an A element descendant of an ? element ' / . as part of its e%pression. first child of its parent ':last(child an ? element. an A element immediately preceded y an ? element ' 1 .doc / M . the nKth child of its parent ':first(child an ? element. ut nonetheless supported y jQuery ' warning an ? element whose class is 'warning' '-+yid an ? element with . an A element preceded y an ? element '2. at most. along with some custom #SSKli!e functionality *and @3ath/. one element. only child of its parent ':e+pty an ? element that has no children *including te%t nodes/ ':ena.CSS Selectors jQuery has full #SS 5K4 support and partial #SS C support.ar5 an ? element whose 'foo' attri ute "alue egins e%actly with the string ' ar' '43foo86.2G select all ? elements. Aor info on how #SS wor!s feel free to read the "arious lin!s: • #SS 5 • #SS 4 • #SS C )hat follows is a list of supported #SS Selector e%pressions.led a user interface element ? which is not disa led ':disa. last child of its parent ':only(child an ? element. A elements. • • • • • • '43foo5 an ? element with a 'foo' attri ute '43foo6. • • • • • • • • • • • • • • • • • • • & any element ' an element of type ? ':nth(child)n* an ? element.ar5 an ? element whose 'foo' attri ute "alue contains the su string ' ar' '43foo6.a96. but different $ll attri ute selectors are written li!e their @3ath counterKparts *in that all attri utes should egin with an 3 sym ol/. *)ill only match.ar5 an ? element whose 'foo' attri ute "alue ends e%actly with the string ' ar' '43foo&6.

(ere are some samples: Location Paths • .efore generated content efore an ? element • '::after generated content after an ? element jQuery doesn<t support the following selectors due to their lac! of realKworld usefulness: • ':nth(last(child)n* an ? element. tml. unli!e real #SS..-"1 t is) $(".Not supported jQuery only supports selectors that actually select 012 elements K e"erything else is ignored. • '::first(line the first formatted line of an ? element • '::first(letter the first formatted letter of an ? element • '::selection the portion of an ? element that is currently selected/highlighted y the user • '::.. counting from the last one • ':nth(of(type)n* an ? element. jQuery supports asic @3ath e%pressions. the nKth child of its parent.doc / 6 .body. for instance with the function $(e$"r1 conte$t). last si ling of its type • ':only(of(type an ? element. XPath Selectors 1ne of the selector languages that jQuery supports. as a part of its e%pression language is @3ath. first si ling of its type • ':last(of(type an ? element.6:en:5 an ? element whose 'hreflang' attri ute has a hyphenKseparated list of "alues eginning *from the left/ with 'en' Context and Anchoring .. the nKth si ling of its type • ':nth(last(of(type)n* an ? element. Bou can anchor a #SSKli!e e%pression to the conte%t root y starting it with one of the selectors >. • ':link • ':%isited an ? element eing the source anchor of a hyperlin! of which the target is not yet "isited *:lin!/ or already "isited *:"isited/ • ':acti%e • ':ho%er • ':focus an ? element during certain user actions • ':target an ? element eing the target of the referring +.."") $("". counting from the last one • ':first(of(type an ? element.. 2..n jQuery. a selector e%pression may ha"e a conte%t other than the entire document.div") • .". in addition to #SS 5KC.document $("."") $("body. only si ling of its type • ':lang)fr* an element of type ? in language 'fr' • '4foo16:test:5 an ? element whose 'foo' attri ute "alue is a list of spaceKseparated "alues.elati"e to the conte%t node t is $("". or 3.elati"e to the entire (T2. the nKth si ling of its type.a"1 t is) 45678989:.. one of which is e%actly equal to 'test' • '4hreflang.

div#". for $(". :parent Selects all elements which ha"e child elements *including te%t/.in"ut#&c ecked%") • 43foo6=test=5 $ttri ute foo is equal to test $(". :%isi.div."") on the same a%es Supported Predicates • 43foo5 (as an attri ute of foo $(".div.ling ?lement has an element efore it. :odd Selects e"ery other *odd/ element from the matched element set.%") • 4>odelist5 ?lement contains a node list.le Selects all "isi le elements *this includes items that ha"e a display of loc! or inline. :first ?qui"alent to :e@)?* :last Selects the last matched element.Supported Axis Selectors • "escendant ?lement has a descendant element $(". :lt)>* Selects all matched elements whose inde% is less than &.div.nofollo+."") • Preceding Si... The following e%pressions< synta% is ased upon the "arious #SS selectors..div#"%") $(".. of similar names.... so were included. ut were found to e "ery handy. Custom Selectors • • • • • • • • • • :e%en Selects e"ery other *e"en/ element from the matched element set.div 3 form") • Parent Selects the parent element of the element $(".. :contains)=test=* Selects all elements which contain the specified te%t. $(". a "isi ility of "isi le...a%") e%ample: Supported Predicates.doc / 5: ."") • <hild ?lement has a child element $(". and aren<t form elements of type hidden/ 45678989:. :e@)?* and :nth)?* Selects the &th element from the matched element set :gt)>* Selects all matched elements whose inde% is greater than &.a#&ref0... but differently • 4last)*5 or 4position)*6last)*5 ecomes :last $(""(last") • 4?5 or 4position)*6?5 ecomes :e@)?* or :first $(""(first") $(""(e)(*)") • 4position)* A B5 ecomes :lt)B* $(""(lt(4)") • 4position)* / !5 ecomes :gt)!* $(""(gt(5)") Custom Selectors jQuery includes some e%pressions that aren<t a"aila le in either #SS or @3ath.

utton Selects all other uttons *typeE' utton'/.oC Selects all chec! o% fields *typeE'chec! o%'/. :su.+it Selects all su mit uttons *typeE'su mit'/. or are form elements of type hidden/ Some e%amples: $(""(first"). te%tarea. :i+age Selects all form images *typeE'image'/. or a "isi ility of hidden. ide()' orm Selectors There are a few selectors for form elements: • • • • • • • • • • :input Selects all form elements *input. :radio Selects all radio fields *typeE'radio'/.css("font6eig t"1"bold")' $("div( idden").t is recommended to pro"ide a conte%t when using the a o"e: $(. :teCt Selects all te%t fields *typeE'te%t'/.)"1 t is).1 my7orm) This would select all input elements of type radio inside myAorm. +sing :radio is mostly the same as LPtypeEradioQ. :file Selects all Ninput typeE'file'O. select.) 1r. :reset Selects all reset uttons *typeE'reset'/. if you ha"e already a reference to your form: $(.• :hidden Selects all hidden elements *this includes items that ha"e a display of none. $lso a"aila le is :hidden. ut should e slightly faster. Good to !now when wor!ing with large forms.5/ See Also • . :password Selects all password fields *typeE'password'/.test. :. !ore Selectors The jQuery selector system can e e%tended y third parties: • 2ore Selectors 3lugin • 2i!e $lsup on #ustom Selectors • 3atch to allow selection y #SS property *full plugin to e released simultaneously with 5.s o+()' $(". see the description a o"e for details.in"ut(radio.#my7orm (in"ut. :check. utton/.div(contains(. .nteracti"e jQuery selector tester 45678989:.doc / 55 .

echo $xml./. 'write%$'3$co#te#t&. header%. +&.rati#2s. 'u#ctio# put@co#te#ts%$'ile3$co#te#t& ( $' = 'ope#%$'ile3"w"&.= *>?.preve#t)e'ault%&. 2y e%ample uses a php file that reads the 'rating' parameter and returns the num er of ratings and the a"erage rating. )e need some ser"er code for this.appe#d%"<a hre'=. $stored>ati#2s79 = $rati#2.post%"rate.text%& &. (a"e a loo! at rate.&. + <> )e don<t want this e%ample to wor! without $ja%. +&. + i'%isset%$@>?AB?= 7"rati#2"9&& ( $rati#2 = $@>?AB?= 7"rati#2"9. 'or % var i = :.0o#te#t-type1 text/xml. $avera2e = rou#d%array@sum%$stored>ati#2s& / cou#t%$stored>ati#2s&3 D&.html% " ha#-s 'or rati#23 curre#t avera2e1 " 6 $%"avera2e"3 xml&. although it may e possi le.ha#dlers to a#chors $%"/rati#2 a"&.php for the ser"erKside code. $stored>ati#2s = u#serialiCe%'ile@2et@co#te#ts%= *>?&&. that allows the user to rate something.com.>" 6 i 6 "</a> "&. 45678989:.n this part we write a small $ja% application.Rate me: Using Aja . <<php de'i#e%.ready%'u#ctio#%& ( // 2e#erate mar-up $%"/rati#2"&. // add mar-up to co#tai#er a#d apply clic.clic-%'u#ctio#%e&( // stop #ormal li#. put@co#te#ts%= *>?3 serialiCe%$stored>ati#2s&&.clice. $cou#t = cou#t%$stored>ati#2s&.html%&+3 'u#ctio#%xml& ( // 'ormat a#d output result $%"/rati#2"&. i66 & $%"/rati#2"&. just li!e it is done on youtu e.doc / 54 .0 of 'rating'. +&. $%docume#t&.&. i <= F.text%& 6 "3 #umber o' votes1 " 6 $%"cou#t"3 xml&.dat.appe#d%"Elease rate1 "&.php"3 (rati#21 $%this&. $xml = "<rati#2s><avera2e>$avera2e</avera2e><cou#t>$cou#t</cou#t></rati#2s>". // se#d request $. 'close%$'&. we therefore generate the necessary mar!up with jQuery and append it to a container di" with an .3 .

"isit softonic.&. &ote the $("a.&.This snippet generates fi"e anchor elements and appends them to the container element with the id 'rating'.a.php with the content of the anchor as a parameter. This pre"ents that the clic! e"ent is applied again and again to the same lin!s.. you can loo! at an online e%ample.clic-%'u#ctio#%&( ha#dler%'oobar&. $ "ery common pro lem encountered when loading content y $ja% is this: )hen adding e"ent handlers to your document that should also apply to the loaded content.remote"1 t is) query. // i' you #eed the co#text o' the ori2i#al ha#dler3 use apply1 $%. the element with id target. The result returned as a @2. . Bou ha"e specified your call ac! ut need to pass an e%tra parameter. t is refers to a different element: .clic-%'u#ctio#%& ( $%"/tar2et"&. + // add clic. &ow that we<"e loo!ed at some asic $ja%. )hen add!lick8andlers is used as a call ac! for load(). you can delegate to a function. The easiest way to achie"e this is to wrap the call ac! inside another function: // 2et some data var 'oobar = .apply%this3 7'oobar9&. causing a crash e"entually.:'. +&.n the e%ample.is then added to the container.ready%add0lic-Ha#dlers&. To pre"ent code duplication.f you don<t ha"e a we ser"er with 3(3 installed at hand.clic-%'u#ctio#%&( ha#dler. $fterwards. t is is passed as a conte%t: Aor the document ready e"ent. a post request is send to rate..de and clic! on 'RurG ewerten. $nother common pro lem with call ac!s are parameters. Aor a "ery nice e%ample of a rating system that e"en wor!s without =a"aScript.hre'3 add0lic-Ha#dlers&. + $%docume#t&. replacing the anchors. you ha"e to apply these handlers after the content is loaded.load%this. // speci'y ha#dler3 it #eeds data as a paramter 'u#ctio# ha#dler%data& ( //.remote"3 this&. Interesting links for this chapter: • jQuery $ja% 0ocumentation • jQuery $3. t is refers to the document.doc / 5C ..a. a clic! handler is added. +&. for e"ery anchor inside the container.' 2ore documentation of the $ja% methods of jQuery can e found in the $ja% 0ocumentation or on Jisual jQuery filed under $ja%.ha#dler a#d pass 'oobar! $%. let<s add some simple effects and animations to the page. and it therefore searches the entire document for anchors with class remote. K #ontains description and e%amples for append and all other jQuery methods • Thic!>o% K $ jQuery plugin that uses jQuery to enhance the famous light o% 45678989:... ?%ample: 'u#ctio# add0lic-Ha#dlers%& ( $%"a. &ow add#lic!(andlers is called once when the 012 is ready and then e"erytime when a user clic!ed a lin! with the class remote and the content has finished loading. +&. )hen the anchor is clic!ed. )ith $ja% this simple we can co"er quite a lot of ')e 4.

.Sm using a =a"aScript onclic! function that sends a request and recei"e a response in $ja% manners. 5. thereSs an application. o "iously a we application that presents its users with a form. please donSt hesitate to do so and of course. ThereSs a jsp file.U #ut to the chase. $s . $ user su mit the filled form.doc / 5F .ADAE2 DS#>2 DQuery with Struts ! http://www.com/strutsK4/aja%KjsonKwithKstrutsK4 . . rather than using (T2. (ereSs the idea. that contains the form handler and mechanism to su mit the form to a ser"erKside resource. coupled with a =a"aScript file.arya566. my quest to deli"er this feature egins with a Google search for T$ja% with Struts 4. and then the application updated its displayed "alues which related to the changed content without e"er lea"ing the page. hereSs my penciled writing on the issue. uilt the application using the Struts 4 framewor!. 1h. jQuery. and of course. $ja% definitely comes to mind. the applicationSs data ase contents are changed. should there e any error or something else that eg to e criticiGed and laughed at in this post. and Scott Stanlic!. To further simplify requestKresponse communication from the client to the ser"er. $nother ca"eat. $lso a disclaimer. and as .Sm using $ja% su mit mechanism. #had 2ichael 0a"is. $ja% and =S1&. facilitate this transfer with =S1& notations *in itself is a redundant elongation of the word since =S1& already stands 45678989:. enact a proper enlightenment to the author *me/.t is assumed that readers of this article is familiar with Struts 4 Aramewor!.form and su mit tag. some =a"a code snippets depicted in this article is ta!en from 2anning: Struts 4 in $ction written y 0onald >rown.

1 divisio#Game+3 'u#ctio#%data& ( $%. up until the "ery last of the line.action/.css%%(bac-2rou#d1 . The third parameter is a call ac! function. the only element in the clientSs code which has an id of division<ame is a (T2.action./divisio#Game.load=elect%divisio#"ist7"arya:II. is a single function from jQuery *get9:.get9:.H=*G>esult"/> </result-types> 45678989:. had this function in my =a"aScript file to forward the request from client to a certain ser"erKside resource using a jQuery function $.&.passedKin as its second parameter *>.actio#. The call ac! function.list&.page with the updated "alue using a custom and handK made jQuery function load:elect.e#tity.name.for =a"aScript 1 ject >otation/ and with jQuery aid./divisio#=elect. + &.doc / 57 . The function then reads the =S1& string passed in as response./I'I. (ere.'ade*ut%"slow"&. this function also has a second parameter./I8I solid :px. . $%. var divisio#Game = $%. ha"e a struts.add)ivisio#.status. ac! to the ser"er resource called from this function. in"o!ed when the request completes.divisio#. it says that the +.&.n my case..is going to ha"e its division. with parameters sent to the said +.val%&. which is status and not shown here. The =S1& string "alue resulted from the response is passed to this function as its first parameter.& . and then populate a certain select component in the resulted (T2.a#imate%(opacity1 :+3 :F88& . select an element from a 012 *0ocument 1 ject 2odel/ that made up the clientSs (T2. $. var divisio#"ist = %data.</ and it has three parameters passed in.passedKin as its first parameter *add=ivision. using a standard *and hopefully tri"ial/ jQuery. The first line of the code. The second line..+&& .3 border1 .name parameter sets to a "alue ta!en from "aria le identified y division<ame/. using a standard and wellK!nown VIS notation for jQuery.standard te%tfield.)ivisio#"9&. and store it in a "aria le called division<ame.'adeJ#%"slow"& . . add=ivision.actio#. . This function initiates a G?T request to the ser"er to the specified +.3 (.division.2etH=*G%..$ml configured to map this action.which identified y an id attri ute named division<ame. 1ptionally.<. therefore the first line of this code selects the "alue from this te%tfield. $gain. &ow. (ereSs the configuration: <result-types> <result-type #ame="customH=*G" class="arya:II.( division<ame?.#ame. as shown in the code a o"e then sets the 012 element in the client code identified y a class named status with some simple animation.

from the action class descri ed in third code e%cerpt a o"e *the =a"a one/.doc / 59 .pri#t=tac. Ainally.action request to a Em"loyee@ction class and to the add=ivision method of that class.2et5ll)ivisio#s%&&. you could see that the pre"ious call descri ed in the pre"ious paragraph would set the pri"ate property =ivision *line 5 and further.actio#.?mployee5ctio#"> <result-typeresult-type="customH=*G">divisio#</result-type> </actio#-#ame> . public =tri#2 add)ivisio#%& ( ?#tity ra#sactio# et = 2et?#tity!a#a2er%&.race%&. private "ist<)ivisio#> all)ivisio#. et. Arom the first e%cerpt youSll also see that the request also passed a parameter division. private *bject jso#!odel. the pri"ate property name in this class would ha"e an equi"alent =a"a>eans getter and setter method which are not shown/ from this class to hold the "alue division<ame passed in from the client.be2i#%&. 45678989:. the @2. &ow hereSs some of the Em"loyee@ction classS contents. + // Ketter a#d setter methods are #ot show# 'or simplicity &ow if you loo! into the first code e%cerpt *the =a"aScript one/ line num er two.persist%divisio#&.one/.action which mapped with the method add=ivision from Em"loyee@ction class through a struts. youSll see that the client called add=ivision.$ml configuration *second code e%cerpt. try ( et. this parameter would translate into a call to set=ivision(args). retur# =B00?==. y the way: private )ivisio# divisio#.commit%&.t is easy to see that line num er F of the code a o"e mapped add=ivision.set<ame(args) from the called action class with a proper "alue passed in as its argument.name with a "alue identified y division<ame. )ith Struts 4 Aramewor!. + setH=*G!odel%2e#eric?#tity. + catch %?xceptio# ex& ( ex. 2et?#tity!a#a2er%&.<actio# #ame="add)ivisio#" method="add)ivisio#" class="arya:II.2et ra#sactio#%&.

and hereSs the e%cerpt of that class.alias%class5lias3 jso#!odel.2et>espo#se%&.action is mapped with a type custom9:. youSll see that the result of the add=ivision.2etMriter%&. public =tri#2 2et0lass5lias%& ( retur# class5lias.bAect class. + xstream. Nalue=tac. =tri#2 class5lias. 1ne ca"eat. >ac! to the configuration @2. i' %class5lias == #ull& ( class5lias = "object".toO!"%jso#!odel&&. respo#se=tream. 4.class5lias = alias. *bject jso#!odel = value=tac-.<. + Eublic void execute%5ctio#J#vocatio# i#vocatio#& throws ?xceptio# ( =ervlet5ctio#0o#text. on line 58 of the action class e%ample a o"e. O=tream xstream = #ew O=tream%#ew Hettiso#!appedOml)river%&&.get@ll=ivisions() method e%ecution. we sets a property called AsonBodel with a "alue o tained from genericEntity.$ call to add=ivision method *line 8 and eyond/ then tells the =3$ *=a"a 3ersistence $3. This step pushes an o ject from the e%ecuted action class to a Dalue:tack and then informs the framewor! a out this o ject and its type *9:. this type is defined properly in line 4.= i#vocatio#. &ow.shown in the second code e%cerpt line 7. Eri#tMriter respo#se=tream = =ervlet5ctio#0o#text.action. This method *not shown/ retrie"es all the 0i"ision o jects from the data ase and populated them into an instance of Cist. that this property *AsonBodel/ is set to hold an instance of .pri#tl#%xstream.doc / 58 .</esult/.2et=tac-%&.9:. public class H=*G>esult impleme#ts >esult ( public static 'i#al =tri#2 )?L5B" @E5>5! = "class5lias". and treats it as a result./ to persist this newly created di"ision o ject to the data ase.set0o#te#t ype%"text/plai#"&.'i#dNalue%"jso#!odel"&.</esult. $lso note. + public void set0lass5lias%=tri#2 alias& ( this. mapped to a class called aryaEFF.2et>espo#se%&.value=tac. + + 45678989:.2et0lass%&&.

etter head to =S1& for a proper e%planation.. . The final step is to sent ac! the =S1& String to the client. the whole =S1& String is returned and stored in a "aria le called data.0i"isionU:LW'id':5. To shorten the discussion.listL'arya566.&.W'id':4. as .entity. data. Ainally. $%. The only pro lem was to determine how the resulted string is returned ac! from the ser"er. WUlistU:WUarya566. the result String loo!s li!e this. and =S1& treats this "aria le as any other o ject.'XQX.'name':'Sales 0epartment'X.doc / 5M .. i. achie"ed this with helps from @Stream li rary and =ettison li rary. $ny class that implemented /esult class therefore needs to implement e$ecute method *line 57/. a string "alued TSales 0epartment.list would yield WUarya566. the resulted "alue is con"erted to a something else *alas. the method implemented here said that itSs going to return a response within a Tte%t/plainU content type.U 45678989:.0i"isionU:LW'.e#tity. therefore. (owe"er.entity.#ame would yield the first name element which according to this case.C.'name':'$ccounting 0epartment'XQXX .n my case. The first line VlistS is o "iously refer to the same word VlistS as shown in the result.list7"arya:II. . and it is.list&. F.0i"ision'Q and passed it to a function that populates the select element with "alues o tained from this array. .entity. $s we could see from the first code e%cerpt *the =a"aScript one/. hereSs how . a class needs to implement /esult class which is e%actly what this class did as shown in line num er one.)ivisio#"9&.e#tity.n order to get a proper treatment as a result y the Struts 4 framewor!.e. then loo!s into Dalue:tack for a "alue idKed with a string "AsonBodel" which as shown in the third code e%cerpt *the =a"a action class code/ a o"e sets to hold "alue returned from a query of all =ivision entity stored in the data ase. calling data. need to see more of it/ representa le as =S1& string. The second line then o tain the array "alue of data. This is most tri"ial.load=elect%divisio#"ist7"arya:II. .f this notation loo!s alien to you. want to populate my select element with these data./divisio#=elect. var divisio#"ist = %data.)ivisio#"9789. retrie"ed the meaningful data from the returned String *also shown in the first code e%cerpt of this article/.

+ +& + 45678989:../validatio#.value. 1 'ieldGame.#ame.class = .style.style.f you want to use $=$@ to do some ser"erKside "alidation *and you<r using =Query/ this should at least get you started: 'u#ctio# validate%'ieldGame& ( $.doc / 56 .com/questions/75:MFC/aja%K"alidationsKinKstrutsK4 .class = . 1 'ieldGame.#ame+3 'u#ctio#%data3 text=tatus& ( i'%data& ( 'ieldGame.2et%.3 (..http://stac!o"erflow. + else ( 'ieldGame.i#validLormJ#put.php.value3 .validLormJ#put.