I want to create a drop-down list with countries and the second drop-down list with cities, which depends on selected value in the first list. And the list of cities should be changed dynamically.
In the view (Thymeleaf) I have a Map<CountryModel, Set<RegionModel>> from controller. CountryModel's name should be shows in the second drop-down list, and Set should be shows in the second(dependent) drop-down list.
Here I create first drop-down list:
 <tr>
   <td th:text="#{country}"/>
   <td>
      <div class="form-group">
          <select th:field="*{transferRequestModel.country}" class="form-control" id="country">
                <option th:each="country : ${transferModel.countries}"
                    th:value="${country}"
                    th:text="${country.key.countryName}">Wireframe
                </option>
          </select>
      </div>
    </td>
 </tr>
So how to create second drop-down list which depends on selected country in the first list?
So I have solved my problem with AJAX request and jQuery append.
Change Map<CountryModel, Set<RegionModel>> to Map<String, Set<String>>
AJAX request
function sendAjaxRequest() {
    var country = $("#country").val();
    $.get( "/regions?country=" + country, function( data ) {
        $("#region").empty();
        data.forEach(function(item, i) {
            var option = "<option value = " + item + ">" + item +  "</option>";
            $("#region").append(option);
        });
    });
};
Use sendAjaxRequest() when i change first drop-down list.
$(document).ready(function() {
    $("#country").change(function() {
        sendAjaxRequest();
    });
});
Drop-down list at the Thymeleaf template
First drop-down list
<td th:text="#{country}"/>
<td>
    <div class="form-group">
        <select th:field="*{model.country}" class="form-control" id="country">
            <option th:each="country : ${model.countries}"
                    th:value="${country}"
                    th:text="${country}">Wireframe
            </option>
        </select>
    </div>
</td>
Second drop-down list
<td>
    <div class="form-group">
        <select th:field="*{requestModel.region}" class="form-control" id="region">
        </select>
    </div>
</td>
Controller
@RequestMapping(value = "/regions")
@ResponseBody
public Set getRegions(@RequestParam String country) {
    Map<String, Set<String>> regions = regionsService.getRegions();
    return regions.get(country);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With