Search code examples
javascriptthymeleaf

Populating a drop down with a array of values passed from JavaScript


I have a Drop down which shows continents. Based on the selection of continent the next Drop down will show the relevant countries of that continent.This is how I did it

<label for="website">Continent</label>
   <Select  class="form-control" th:field="*{continent}" id="continent">
         <option th:value="Africa" th:text="Africa"></option>
         <option th:value="Europe" th:text="Europe"></option>
         <option  th:value="Asia" th:text="Asia"></option>
</Select>



<label for="website">Country</label>
<Select  class="form-control" th:field="*{country}" id="country">  </Select>               

Here is the JavaScript Code I used to do that

<script>
    var select = document.getElementById('continent');

    select.addEventListener("change",function() {
        passValue(this.value);
    });

    function passValue(x) {
        var a = x;
        if (a=='Asia'){
            var options=['China','India','Pakistan','Malaysia']
        }else if (a == 'Europe'){
            var options=['UK','Switzerland','Germany','France']
        }else if(a=='Africa'){
            var options=['South Africa','Ethiopia','Kenya','Moroco']
        }


        var select = document.getElementById("country");
        for(var i = 0; i < options.length; i++) {
            var opt = options[i];
            var el = document.createElement("option");
            el.textContent = opt;
            el.value = opt;
            select.appendChild(el);
        }
    }

If I select a continent for an example Europe, the countries in Europe are shown on the second Drop down as I expected. But if I select another continent for a example Asia, then all the countries in previous selection and current selection (countries in Europe and Asia) are shown on the second Drop down

After Selecting Europe on Drop down 1

Selecting Asia on Drop down 1 after selecting Europe

Please give a solution for this issue.


Solution

  • You could set first the options in dropdown to empty before you append again those new options, like this one

    if you use Jquery:

    $('#country').empty()
    

    if you use pure JS

    document.getElementById("country").innerHTML ="";