Thursday, August 25, 2011

In JSP, Rendering a dropdrownlist on the basis of another dropdownlist's selection value

Its a little bit difficult to change a drop down list on basis of another selected value of drop down list in jsp. To do so, we need to use help from ajax. And the specific function of the ajax file is called onchange event of the (decision maker) drop down list.


onchange="loadDDLfirst()"

The loadDDLfirst() file is written in a javascript file(i.e, name of the javascript file is ajaxjs.js)




//////////////---Code of ajaxjs.js----///////////////////////
var xmlhttp;

var nm;
function loadDDLfirst()
{

/*To save the name of the District*/

var w = document...selectedIndex;
var selected_text = document...options[w].text;
document..selected_District.value=selected_text;

/////-----------------------------/////
var districtID;
parameterValue = document.getElementById("ddlFirst").value;

xmlhttp=GetXmlHttpObject();

if (xmlhttp==null)
{
alert ("Your browser does not support Ajax HTTP");
return;
}

//////////////---End of code of ajaxjs.js----///////////////////////


/* Actually the drop down list is generated at another webpage consisting on the dropdown list. And each time a random no. is added with the url to make identity of the request*/
url ="<webpageurl>?=" + parameterValue + "&idn=" + Math.random() * 100;
xmlhttp.onreadystatechange=getValues;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function getValues()
{
if (xmlhttp.readyState==4)
{
document.getElementById("load_ddl2ND").innerHTML=xmlhttp.responseText;
}
}


load_ddl2ND is the id of the form element where the webpageurl.jsp page will be showed. The webpageurl.jsp contains the code to create the dropdownlist.


<%
///Code to load simple dropdownlist as in normal jsp
%>



No comments: