Dependent drop-down list from map in Thymeleaf

后端 未结 2 1380
我在风中等你
我在风中等你 2021-01-06 17:52

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

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-06 17:53

    So I have solved my problem with AJAX request and jQuery append.

    1. Change Map> to Map>

    2. AJAX request

      function sendAjaxRequest() {
          var country = $("#country").val();
          $.get( "/regions?country=" + country, function( data ) {
              $("#region").empty();
              data.forEach(function(item, i) {
                  var option = "";
                  $("#region").append(option);
              });
          });
      };
      
    3. Use sendAjaxRequest() when i change first drop-down list.

      $(document).ready(function() {
          $("#country").change(function() {
              sendAjaxRequest();
          });
      });
      
    4. Drop-down list at the Thymeleaf template

    First drop-down list

    
    
        

    Second drop-down list

    
        
    1. Controller

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

提交回复
热议问题