Rodik
Rodik

Reputation: 271

Assign a select dropdown value to Spring MVC variable

Hello i'm having a problem when I want to display some data.

I have a list of countries and each country contains a list of regions.

What I want to do after choosing the country. I want my 2nd list to take pays.regions

Below my form :

              <form:form method="POST" modelAttribute="modelForm" action="${myAction}">
                  <label>Pays</label>
                  <form:select path="isoCode">
                  <form:options items="${pays}" itemValue="isocode" itemLabel="name"/>
                  </form:select>
                           
                  <label>regions</label>
                  <form:select path="region>
                  <form:options items="valueSelected.regions" itemValue="region" itemLabel="name"/>
                  </form:select>
            </form:form>

I want to put the value selected from pays in a variable and use it in select for regions.

Thank you in advance.

Regards,

Upvotes: 1

Views: 58

Answers (1)

CHARAFI Saad
CHARAFI Saad

Reputation: 1440

You to use JavaScript for this use case

Use this :

<script type="text/javascript">

var pays = new Array();

<c:forEach items="${pays}" var="country" varStatus="status">
var regions = new Array();
<c:forEach items="${country.regions}" var="region" varStatus="status">
regions.push({id: "${region.isocode}", name:"${region.name}"});
</c:forEach>
countries.push({id: "${country.isocode}", name:"${country.name}" , regions: regions });
</c:forEach>

function functionOnChange()
{
 let country = document.getElementById('your-country-selector').value;
 let regionsCountry = countries.find(c => c.id == country).regions;

 let selectorRegions = document.getElementById('your-region-selector');

  selectorRegions.innerHTML = "";

  regionsCountry.forEach(r => {
    let option = document.createElement("option");
    option.value = r.isocode
    option.innerHTML = r.name
    selectorRegions.appendChild(option)
});

}
</script>

And remove the options from your tag

Upvotes: 1

Related Questions