Dependant Dropdowns Using Ajax
below has 2 combo boxes 1.country 2.city.
OnChange event on the country should populate the corresponding cities in the
city dropdown.
1 2 -------------------------------------------------------------------------------- 3 ajaxscripting.js 4 -------------------------------------------------------------------------------- 5 6 <script type="text/javascript"> 7 var xmlHttp; 8 function createXMLHttpRequest() { 9 if (window.ActiveXObject) { 10 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 11 } 12 else if (window.XMLHttpRequest) { 13 xmlHttp = new XMLHttpRequest(); 14 } 15 } 16 17 function doRequestUsingGETCountry(url) { 18 19 createXMLHttpRequest(); 20 queryString = url ; 21 queryString = queryString + "&selcountry="+document.forms[0].country.options[document.forms[0].country.selectedIndex].value; 22 xmlHttp.onreadystatechange = handleStateChange; 23 xmlHttp.open("GET", queryString, true); 24 xmlHttp.send(null); 25 } 26 27 function handleStateChange() { 28 if(xmlHttp.readyState == 4) { 29 if(xmlHttp.status == 200) { 30 parseResults(); 31 } 32 } 33 } 34 function parseResults() { 35 var responseText = document.createTextNode(xmlHttp.responseText); 36 var returnElements=xmlHttp.responseText.split("||"); 37 //Process each of the elements 38 for ( var i=0; i<returnElements.length; i++ ){ 39 40 if(returnElements[i]!="") 41 { 42 valueLabelPair = returnElements[i].split(";") 43 document.getElementById('state').options.length= returnElements.length; 44 document.getElementById('state').options[i] = new Option(valueLabelPair[0], valueLabelPair[1]); 45 } 46 } 47 } 48 function inc(filename) 49 { 50 var body = document.getElementsByTagName('body').item(0); 51 script = document.createElement('script'); 52 script.src = filename; 53 script.type = 'text/javascript'; 54 body.appendChild(script) 55 } 56 57 -------------------------------------------------------------------------------- 58 dependantComboExample.jsp 59 -------------------------------------------------------------------------------- 60 <%@page import="ajaxsample.SampleForm,java.util.*"%> 61 <%@include file="taglibs.jsp"%> 62 <%@include file="ajaxscripting.js"%> 63 64 <head> 65 </head> 66 67 <body onLoad="doRequestUsingGETCountry('/struts-ajax/DependantComboExample.do?');"> 68 69 <html:form action="DependantComboExample.do" > 70 71 <h1></h1> 72 <table> 73 <tbody> 74 <tr> 75 <td>Country</td> 76 <td> 77 <html:select property="country" name="inputForm" onchange="doRequestUsingGETCountry('/struts-ajax/DependantComboExample.do?');"> 78 <html:options collection="countries" property="value" labelProperty="label"/> 79 </html:select> 80 </td> 81 <td> 82 <html:select property="state" name="inputForm" > 83 <html:options collection="states" property="value" labelProperty="label" /> 84 </html:select> 85 </td> 86 </tr> 87 </tbody> 88 </table> 89 90 </html:form> 91 </body> 92 </script> 93 94 ------------------------------------------------------------------ 95 GetAndPostExample 96 ------------------------------------------------------------------ 97 98 99 package ajaxsample; 100 101 import java.io.*; 102 import java.net.*; 103 import javax.servlet.*; 104 import javax.servlet.http.*; 105 import org.apache.struts.action.Action; 106 import org.apache.struts.action.ActionForm; 107 import org.apache.struts.action.ActionForward; 108 import org.apache.struts.action.ActionMapping; 109 import java.util.ArrayList; 110 import org.apache.struts.action.ActionServlet; 111 import org.apache.struts.util.LabelValueBean; 112 113 public class GetAndPostExample extends Action { 114 115 ServletContext context = null; 116 117 public void setServlet(ActionServlet servlet) 118 { 119 context = servlet.getServletContext(); 120 } 121 public ActionForward execute(ActionMapping mapping, ActionForm inForm, 122 HttpServletRequest request, HttpServletResponse response) throws Exception { 123 response.setContentType("text/xml"); 124 125 String optionSelected = request.getParameter("selcountry"); 126 //Build the response text 127 128 SampleForm sform = (SampleForm)inForm; 129 ArrayList countries = (ArrayList)context.getAttribute("countries"); 130 ArrayList states = (ArrayList)context.getAttribute("states"); 131 ArrayList newStates = new ArrayList(); 132 String responseText = ""; 133 //sending response text in the format label:value||label;value 134 for(int i=0;i<states.size();i++) 135 { 136 LabelValueBean temp = (LabelValueBean)states.get(i); 137 if(temp.getValue().startsWith(optionSelected)) 138 { 139 newStates.add(temp); 140 responseText = temp.getLabel()+";"+temp.getValue()+"||"+responseText; 141 } 142 } 143 if(responseText.endsWith("||")) //chop off the ending || 144 { 145 responseText = responseText.substring(0, responseText.lastIndexOf("||")); 146 } 147 PrintWriter out = response.getWriter(); 148 out.println(responseText); 149 //Close the writer 150 out.close(); 151 return(mapping.findForward("content1")); 152 } 153 } 154 ------------------------------------------------------------------ 155 CacheServlet.java 156 ------------------------------------------------------------------ 157 158 package ajaxsample; 159 160 import javax.servlet.http.HttpServlet; 161 import javax.servlet.http.HttpServletRequest; 162 import javax.servlet.http.HttpServletResponse; 163 import javax.servlet.ServletConfig; 164 import javax.servlet.ServletException; 165 import java.io.IOException; 166 import org.apache.struts.util.LabelValueBean; 167 import java.util.*; 168 /** 169 * 170 * @author rupali_l 171 */ 172 public class CacheServlet extends HttpServlet { 173 174 175 /** Creates a new instance of CacheServlet */ 176 public void init() throws ServletException { 177 178 179 System.out.println("In do get of CacheServlet"); 180 ArrayList countries = new ArrayList(); 181 countries.add(new LabelValueBean("India", "1" )); 182 countries.add(new LabelValueBean("U.S","2")); 183 countries.add(new LabelValueBean( "Australia","3")); 184 185 ArrayList states = new ArrayList(); 186 states.add(new LabelValueBean("Maharashtra","11")); 187 states.add(new LabelValueBean( "Delhi","12")); 188 states.add(new LabelValueBean("Goa","13")); 189 states.add(new LabelValueBean( "Newjersey","21")); 190 states.add(new LabelValueBean("NewYork","22")); 191 states.add(new LabelValueBean( "California","23")); 192 states.add(new LabelValueBean("Sydney","31")); 193 getServletContext().setAttribute("countries", countries); 194 getServletContext().setAttribute("states", states); 195 196 197 } 198 199 200 public void doGet(HttpServletRequest request ,HttpServletResponse response) throws ServletException, 201 IOException 202 { 203 // request.getRequestDispatcher 204 } 205 206 207 } 208 ------------------------------------------------------------------ 209 web.xml 210 ------------------------------------------------------------------ 211 212 213 <web-app> 214 <display-name>Struts Blank Application</display-name> 215 216 <!-- Standard Action Servlet Configuration (with debugging) --> 217 <servlet> 218 <servlet-name>CacheServlet</servlet-name> 219 <servlet-class>ajaxsample.CacheServlet</servlet-class> 220 <load-on-startup>1</load-on-startup> 221 </servlet> 222 223 224 <servlet> 225 <servlet-name>action</servlet-name> 226 <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> 227 <init-param> 228 <param-name>config</param-name> 229 <param-value>/WEB-INF/struts-config.xml</param-value> 230 </init-param> 231 <init-param> 232 <param-name>debug</param-name> 233 <param-value>2</param-value> 234 </init-param> 235 <init-param> 236 <param-name>detail</param-name> 237 <param-value>2</param-value> 238 </init-param> 239 <load-on-startup>2</load-on-startup> 240 </servlet> 241 242 <!-- Standard Action Servlet Mapping --> 243 <servlet-mapping> 244 <servlet-name>action</servlet-name> 245 <url-pattern>*.do</url-pattern> 246 </servlet-mapping> 247 248 249 <!-- The Usual Welcome File List --> 250 <welcome-file-list> 251 <welcome-file>index.jsp</welcome-file> 252 </welcome-file-list> 253 254 255 <!-- Struts Tag Library Descriptors --> 256 <taglib> 257 <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri> 258 <taglib-location>/WEB-INF/struts-bean.tld</taglib-location> 259 </taglib> 260 261 <taglib> 262 <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri> 263 <taglib-location>/WEB-INF/struts-html.tld</taglib-location> 264 </taglib> 265 266 <taglib> 267 <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri> 268 <taglib-location>/WEB-INF/struts-logic.tld</taglib-location> 269 </taglib> 270 271 <taglib> 272 <taglib-uri>/WEB-INF/struts-nested.tld</taglib-uri> 273 <taglib-location>/WEB-INF/struts-nested.tld</taglib-location> 274 </taglib> 275 276 <taglib> 277 <taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri> 278 <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location> 279 </taglib> 280 281 </web-app> 282 283 struts-config.xml 284 285 286 <!-- ================================================ 287 <struts-config> 288 <!-- ================================================ 289 290 <form-beans> 291 292 <!-- <form-bean name="sampleForm" type="ajaxsample.SampleForm"/> 293 --> 294 295 <!-- sample form bean descriptor for an ActionForm--> 296 <form-bean 297 name="inputForm" 298 type="ajaxsample.SampleForm"/> 299 </form-bean> 300 301 </form-beans> 302 <action-mappings> 303 <action path="/DependantComboExample" type="ajaxsample.GetAndPostExample" 304 name="inputForm" scope="request" validate="false" > 305 306 <!-- Partial Ajax Content--> 307 <forward name="content1" path="/dependantComboExample.jsp" /> 308 309 </action-mappings> 310 311 </struts-config> 312 313 314 315