I've a pair of state/city drop down selects in a form. The city drop down should be dynamically changed depending of the state selected by the user. I'm using jQuery with Spring MVC.
My object of states/cities is a HashMap of HashMaps, so, for state '01' (first key), I've got cities 001 (second key) - city1 (value) and 002 (second key) - city2 (value):
LinkedHashMap<String,LinkedHashMap<String, String>> enumsCountyByDistrict = new LinkedHashMap<String,LinkedHashMap<String, String>>();
LinkedHashMap<String, String> districtCounties = new LinkedHashMap<String, String>();
for (City en : cities)
districtCounties.put(en.getCode(), en.getDescription());
enumsCountyByDistrict.put(district, districtCounties);
where cities is a list which I retrieve from database.
I'm passing this object to my view with:
modelAndView.addObject("countiesByDistrict", enumsCountyByDistrict);
modelAndView.addObject("districts", districts);
Where districts is the lists of the different states.
Now, my JSP shows the values with form:selects :
<div class="span3">
<label> <fmt:message key="create.district" /></label>
<form:select id="addressdistrict" path="person.addressdistrict">
<c:forEach items="${districts}" var="item">
<form:option value="${item.code}" label="${item.description}" />
</c:forEach>
</form:select>
</div>
<div class="span3">
<label> <fmt:message key="create.county" /> </label>
<form:select path="person.addresscounty" id="addresscounty">
<form:options items="${countiesByDistrict['13']}" />
</form:select>
</div>
I'm hardcodding countiesByDistrict['13'] to show the cities of district 13, and it does it ok, but now, obviously, I want it to change depending of the code selected at addressdistrict form:select.
Anyone can help?
Make an ajax call to get the list of cities and update your other select box. If you don't want to do ajax call or the list of cities is small fetch both details in initial page request and use javascript/jquery to update. Check this question jquery-json-to-populate-dropdown-list,
I think i faced a pretty much similar issue, i had a structure like follows:
and i needed to dinamically update the option values available in the selects with ids *add_rule_form_rules[i].attribute*
so i used the following jquery code:
Of course you still need the server side component to return a JSON (or xml if you prefer) response containing the value available for a specific ambit selected