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)
populateDropDown()
};
}
else
{
alert('Your browser can\'t handle this script');
return;
}
//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
xmlDoc.load(url);
}
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--)
{
dd3.options[q]=null;
}
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:
