Зависимый выпадающий список с карты в Thymeleaf



Я хочу создать выпадающий список со странами и второй выпадающий список с городами, который зависит от выбранного значения в первом списке. И список городов должен меняться динамически.
В представлении (Thymeleaf) у меня есть Map<CountryModel, Set<RegionModel>> от контроллера. Имя CountryModel должно быть показано во втором раскрывающемся списке, а Set-во втором(зависимом) раскрывающемся списке.

Здесь я создаю первый выпадающий список:



 <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>


Итак, как создать второй выпадающий список, который зависит от выбранной страны в первом списке?

1079   2  

2 ответов:

Таким образом, я решил свою проблему с AJAX-запросом и jQuery append.

  1. Изменить Map<CountryModel, Set<RegionModel>> на Map<String, Set<String>>

  2. AJAX-запрос

    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);
            });
        });
    };
    
  3. Используйте sendAjaxRequest(), когда я изменяю первый выпадающий список.

    $(document).ready(function() {
        $("#country").change(function() {
            sendAjaxRequest();
        });
    });
    
  4. Выпадающий список в шаблоне Thymeleaf

Первый выпадающий список

<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>

Второй выпадающий список

<td>
    <div class="form-group">
        <select th:field="*{requestModel.region}" class="form-control" id="region">
        </select>
    </div>
</td>
  1. Контроллер

    @RequestMapping(value = "/regions")
    @ResponseBody
    public Set getRegions(@RequestParam String country) {
        Map<String, Set<String>> regions = regionsService.getRegions();
        return regions.get(country);
    }
    

В нашем проекте мы сделали это так:

<div class="form-group">
    <label class="col-sm-4 control-label" 
           th:text="#{person.edit.policy.tfoms}"></label>

    <div class="col-sm-8">
        <select class="form-control" th:field="*{tfoms}" 
                onchange="loadInsuranceCompanies()">
            <option th:each="t : ${tfomses}" 
                    th:value="${t.uidtfoms}"  
                    th:text="${t.shortName}"
                    th:selected="${personBean.tfoms != null 
                    and personBean.tfoms.equals(t)}">
            </option>
        </select>
    </div>
</div>
<div th:class="${#fields.hasErrors('insuranceCompany')} 
     ? 'form-group has-error' : 'form-group'">
    <label class="col-sm-4 control-label" 
          th:text="#{person.edit.policy.ic}">
    </label>

    <div class="col-sm-8" id="insuranceCompaniesContent">
        <select class="form-control" id="insuranceCompany" 
                name="insuranceCompany"  
                th:fragment="insuranceCompany">
            <option th:each="i : ${insuranceCompanies}" 
                    th:value="${i.uidinsurancecompany}"  
                    th:text="${i.shortName}"
                    th:selected="${personBean.insuranceCompany != null 
                    and personBean.insuranceCompany.equals(i)}">
            </option>
        </select>
        <div th:if="${#fields.hasErrors('insuranceCompany')}" 
         th:each="err : ${#fields.errors('insuranceCompany')}">
        <span class="text-danger" th:text="${err}"></span><br/>
        </div>
    </div>
</div>

Функция загрузки страховых компаний loadInsuranceCompanies():

function loadInsuranceCompanies() {
    var url = /*[[@{/PersonEdit/insuranceCompanies}]]*/ "/PersonEdit/insuranceCompanies";
    if ($('#tfoms').val() !== '') {
        url = url + '/' + $('#tfoms').val();
    }
    $("#insuranceCompaniesContent").load(url);
}

И, наконец, код в контроллере:

@RequestMapping(value = "/PersonEdit/insuranceCompanies/{tfoms}", method = RequestMethod.GET)
public String getInsuranceCompaniesByTfoms(@PathVariable("tfoms") Integer tfomsId,
        Model model) {
    model.addAttribute("insuranceCompanies", insuranceCompanyService
            .getInsuranceCompaniesByTfoms(new TerritorialFondOms(tfomsId)));
    return "person/PersonEdit :: insuranceCompany";
}

Comments

    Ничего не найдено.