BenSV
BenSV

Reputation: 169

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.

Upvotes: 1

Views: 100

Answers (2)

Qonvex620
Qonvex620

Reputation: 3972

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 ="";

Upvotes: 1

Cody Wall
Cody Wall

Reputation: 167

You need to clear your options variable on subsequent clicks so it won't keep adding onto what's already there. This should do the trick.

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

Upvotes: 0

Related Questions