Monday, January 29, 2007

Dynamic Dropdown List using AJAX

I wanted to discover how to use AJAX to populate a dynamic dropdown list based on the input of some controls on the current page.

There are 2 dropdown lists which determine the elements of the third dropdown list.

Please see the live demonstration Here

The sample code (jsp and php) can be downloaded at Sample Code

Basically on the onchange event of the first 2 dropdowns, there will be an ajax call to retrieve values for the third dropdown.

There are 3 files:

1. dropdownPage.jsp(php) - main page which makes backend calls to retrieve the 3rd dropdown values
2. dataPage.jsp(php) - which provides the server data(nested xml) for the third dropdown
3. dropdownResults.jsp(php) - which simply shows which values the user has selected

The heart of the code is in the javascript processing on the dropdownPage.jsp:

AJAX Scripting (JSP Version):

function importXML()
if (document.implementation && document.implementation.createDocument)
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.onload = populateDropDown;
else if (window.ActiveXObject)
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.onreadystatechange = function ()
{ if (xmlDoc.readyState == 4)
alert('Your browser can\'t handle this script');

//determine url to get xml
var dd1Param = document.f1.dd1.value;
var dd2Param = document.f1.dd2.value;
var url = 'dataPage.jsp?dd1='+dd1Param+'&dd2='+dd2Param;
//load the xml

function populateDropDown()

var browser = 'ie';
var nameIndex = 0;
var valueIndex = 1;
if (document.implementation && document.implementation.createDocument)
browser = 'firefox';
var nameIndex = 1;
var valueIndex = 3;

var dd3 = document.f1.dd3;

//empty control
for (var q=dd3.options.length;q>=0;q--)

var x = xmlDoc.getElementsByTagName('item');
for (j=0;j < x[0].childNodes.length;j++)
if (x[0].childNodes[j].nodeType != 1) continue;
var theData = document.createTextNode(x[0].childNodes[j].nodeName);

for (i=0;i < x.length;i++)
var name = '';
var value = '';
for (j=0;j < x[i].childNodes.length;j++)
if (x[i].childNodes[j].nodeType != 1) continue;
var theData = document.createTextNode(x[i].childNodes[j].firstChild.nodeValue);
if (j==nameIndex) name = theData.nodeValue;
if (j==valueIndex) value = theData.nodeValue;

dd3.options[i] = new Option(name, value);

function submitform()
var dd1 = document.f1.dd1;
var dd2 = document.f1.dd2;
var dd3 = document.f1.dd3;
var dd1Value = dd1.options[dd1.selectedIndex].value;
var dd2Value = dd2.options[dd2.selectedIndex].value;
var dd3Value = dd3.options[dd3.selectedIndex].value;

var page = "dropdownResults.jsp?dd1="+dd1Value+"&dd2="+dd2Value+"&dd3="+dd3Value;
window.location = page;

One thing I do like about this example is that the data read provides a nested xml structure as follows:


turezky said...

This script is awesome! :)
Exactly what I was looking for!
Works with utf-8 like a charm!

Anonymous said...

Can we set different color to the elements in the selection list while building it?


samuel said...

Cool dude ! ! !

Anonymous said...

Hi, a question: How can we modify the scripts in order to make them work with the browser Google Chrome? Thanks!

Aschwin Versteegden said...

I used your code on some of my JSP pages. I liked te setup of your doc. I could implement without a problem.

Anonymous said...

callaway warbird plus golf bag vintage butterfly candle holder makers

Anonymous said...

It is tooooooooooo good.....

Thanx a lot.......

Priya said...


Can you plz help me by replacing the values by data taken from mysql table.

I am new to jsp and need help..

Thx Priya

ajax tab container said...

It seems so easy to learn and apply. It sure is a wonderful thing to learn different kinds of application in order to make the best website.

Anonymous said...

You have a very good blog that the main thing a lot of interesting and useful! erectile dysfunction Read a useful article about tramadol tramadol

Anonymous said...

windows mobile project managment software windows xp install software java download [url=]dvd region codes software[/url] maxsea marine software
[url=]DVD Lab Pro 2.5 - Software Store[/url] gps laptop computer software

Anonymous said...

wki software skids numbering packing software [url=]tasco galaxsee skywatch software updates[/url] ge security downloading software
[url=]Programacion y elaboracion - Download OEM, Software Sale, OEM Software[/url] menstrual cycle software

Anonymous said...

Concerned with the lines and wrinkles in your cheeks, [url=]lifecell cream[/url] to add this chemical p into natural skin care regimen. life cell Not like the majority of accessible products, which simply work with the creases, hydroxatone and examine others too.

Anonymous said...

magnіfіcent iѕѕuеs altοgether, you juѕt gaineԁ
a logo neω reaԁеr. What could you recommend іn regаrds to
yοuг post that you mаԁe a few dаys in the paѕt?

Anу ρositіve?

Mу homeρage: pony oyunları

Anonymous said...

you're actually a good webmaster. The website loading speed is incredible. It kind of feels that you are doing any unique trick. In addition, The contents are masterpiece. you'ѵе peгfoгmed а wonderful proсeѕs in thіs subject!

Review my homepagе ... asker oyunları

Anonymous said...

Аppгeciating the hагd wοrκ уοu
put into yοur blog and іn dеpth information you offer.
Ӏt's great to come across a blog every once in a while that isn't the same old rehashed mаterial.

Great read! I've bookmarked your site and I'm includіng
youг RSS feeds to my Google account.

Ηeгe is my blog post - fox oyunları

Anonymous said...

Whаt's up to every body, it's my first ρаy
a visit of this webpаgе; this wеbsite cаrгies aweѕome and in faсt excellеnt dаta
in suρport οf reaԁerѕ.

Alѕo visit my web sitе; güzel oyunlar

Anonymous said...

Hello! I knоw this іs κіnda off topic nevеrtheless I'd figured I'd aѕk.
Would yοu be іnteгested in exchanging lіnks οr maybe guest
authοring a blog post or νicе-versa? My blog goes oѵer а lot of the same subjectѕ as yours and
I believe we could greаtlу benefit from each otheг.
ӏf you're interested feel free to shoot me an email. I look forward to hearing from you! Terrific blog by the way!

My web site fırlatma oyunları

Anonymous said...

Thank you for the auspicious writeup. It in fact was a amusement account it.
Look advanced to more added agreeable from you! By the
way, how could we communicate?

my blog post ... Best Wrinkle Cream

Anonymous said...

general contractor software free windows shopping cart software [url=]metal fabrication accounting software[/url] dundas software
[url=]EMCO Network Malware Cleaner 4.1 - Software Store[/url] smarttech mp3 player software

Anonymous said...

What's up i am kavin, its my first occasion to commenting anyplace,
when i read this paragraph i thought i could
also create comment due to this brilliant piece of writing.

my blog ... buy sildenafil in new zealand

Anonymous said...

Spot on with this write-up, I honestly think this website needs far more attention. I'll probably be back
again to see more, thanks for the info!

Also visit my blog post: Oriental escorts in London (

Anonymous said...

Did not thought about this until now :)Garcinia Cambogia Extract prevents the pancreatic from breaking up down starch into maltose and dextrin.
It also ceases the production of alpha-amylase nutrients in the entire body.
Doctors usually propose this to their patients who are diabetes patients because the Garcinia Cambogia stops the growth of alpha-glucosidase based in the
intestinal tract from renovating disaccharides and starches into glucose.
Garcinia Cambogia benefits also reduces sugars and carbohydrates from changing into unwanted body fat by stopping the growth of citrate
lyase. Some physicians use Garcinia as a laxative to help with constipation or other well-being reasons such
as dieting, a stress reliever, sadness, changes in mood and as a aid to getting a great night rest.

Here is my blog: pure garcinia cambogia price

Anonymous said...

There is definately a great deal to learn about this
subject. I love all the points you've made.

Feel free to surf to my web page :: Florida motorcycle accident

Anonymous said...

Amazing blog! Is your theme custom made or did you download it
from somewhere? A theme like yours with a few simple adjustements would really make
my blog jump out. Please let me know where you got your theme.
Appreciate it

Feel free to surf to my web-site; Cheap Nike Air Max 1

Anonymous said...

Hi, I think your blog might be having browser compatibility issues.
When I look at your blog site in Ie, it looks fine but when opening in Internet Explorer, it has some overlapping.
I just wanted to give you a quick heads up!
Other then that, excellent blog!

My web site :: repo cars for sale in pacoima,,

Anonymous said...

Hey just wanted to give you a quick heads up. The text in your
post seem to be running off the screen in Internet explorer.
I'm not sure if this is a format issue or something to do with internet browser compatibility but I thought I'd
post to let you know. The design look great though! Hope you
get the problem solved soon. Cheers

Have a look at my webpage :: Skrzynki plastikowe

Anonymous said...

This indicates your gadget is now disconnected from the Computer.

On my blog i've posted all newest tweaks, iOS Downloads etc.
Therefore, unlike Apple, Google desires builders and hackers to play with the code.

Here is my homepage - vshare not installing

Anonymous said...

Aș nici un interes și a respins-o ca prostii complet .
Sau , este timpul acum pentru a modifica ceea ce se oferă , astfel încât
să obțineți pur și simplu un alt tip de practici sexuale
? Fă un duș amendă ; obține toate de tine scartaie - curat .

Feel free to surf to my web-site sex shop bucuresti ()

John son said...

Talk to your family concerning the wishes you have uttered in your Proxy and Living Will and tell them who you have chosen as your Agent and Alternate. Surprise, hard feelings, or controversy around your hospital bed may produce an repulsive situation and could result in your wishes not being pleased.
Massachusetts Estate Planning