user2421594
user2421594

Reputation: 81

Populating select drop down with arrays

Hi got this piece of code which I'm trying to populate based on what the user selects..It does what I want but it is creating duplicates inside the select options which I don't want every time a user selects from the dropdown.

Check it out thanks...https://jsfiddle.net/ncfqLkn5/

var state_province_canada = ['Please select your province', 'AL', 'British Columbia', 'Ontario', 'Quebec'];
var city_canada = [];
    city_canada[0] = ['Please select your city', 'Edmonton T5A 4L8'];
    city_canada[1] = ['Please select your city', 'Coquitlam V3K 3V9', 'Vancouver V6Z1Y6'];
    city_canada[2] = ['Please select your city', 'Brampton L6Z 4N5', 'Sarnia N7T 4X3', 'Strathroy N7G 1Y7', 'Newmarket L3Y 5G8', 'Collingswood L9Y 1W3', 'Corunna N0N 1G0', 'Sarnia N7T 4X3'];
    city_canada[3] = ['Please select your city', 'Sherbrooke J1J 2E4', 'Quebec G1V 4M6', 'St. Charles Borromee J6E 6J2', 'Quebec G1V 4G5', 'Montreal H3H 1A1'];    


$(document).ready(function(){
    $("select").change(function(){
        $( "select option:selected").each(function(){
            if($(this).attr("value")=="canada"){
                $.each(state_province_canada, function(val, text) {
                  $('#state_province').append( $('<option></option>').val(val).html(text) );
                });
                $(".province").hide();
                $("#state_province").show();
            }

            if($(this).text() == "AL") {
              $.each(city_canada[0], function(val, text) {
                  $('#city').append( $('<option></option>').val(val).html(text) );
                });
                $("#city").show();
            }
        });
    }).change();
});

Upvotes: 1

Views: 61

Answers (1)

swornabsent
swornabsent

Reputation: 994

You are .append()ing options to a select element that already has options. The simplest option would be to .empty() the select before you loop through your appends.

if($(this).val()=="canada") {
    $('#state_province').empty();
    $.each(state_province_canada, function(val, text) {
        $('#state_province').append($('<option>').val(val).html(text));
    });
}

Alternatively rather than append in a loop, set html() with a map:

if($(this).val()=="canada") {
    $('#state_province').html($.map(state_province_canada, function(text, val) {
        return $('<option>').val(val).html(text);
    }));
}

Upvotes: 2

Related Questions