Jon L
Jon L

Reputation: 33

Select2 options not getting updated properly

I'm trying to build Country -> State -> City feature in my website where state and city select boxes are disabled and once user chooses a Country it shows that country's respective states and so on.

Issue I'm facing is that once a particular country's states are shown in state input and after that if i change the country then that new country's states are also shown but along with previous country's states.

function states_data(loc_data, selectedCountry) {
    var _states_array = [];
    var states = loc_data[selectedCountry];
    for (i = 0; i < states.length; i++) {
        _states_array.push({
            id: states[i],
            text: states[i]
        })
    }
    return _states_array
}

function _cities(state) {
    var val = Math.floor((Math.random() * 100) + 1);
    return [{
        id: val + state,
        text: val + state
    }];
}
var loc_data = {
    'USA': ['USA State 1', 'USA State 2', 'USA State 3'],
    'Australia': ['AUS State 1', 'AUS State 2']
}

$('#loc_state').select2({
    placeholder: "Select a state",
    disabled: true
}).on('change', function() {
    var selectedState = $(this).val();
    $('#loc_city').select2({
        disabled: false,
        placeholder: "Select a city",
        allowClear: true,
        data: _cities(selectedState)  //it should delete previous values and update new ones.
    });
}).trigger('change');

$('#loc_city').select2({
    placeholder: "Select a city",
    disabled: true
});

var countries_data = [];
for (var key in loc_data) {
    countries_data.push({
        id: key,
        text: key
    });
}

$('#loc_country').select2({
    placeholder: "Select a country",
    allowClear: true,
    data: countries_data
}).on('change', function() {
    var selectedCountry = $(this).val();
    $('#loc_state').select2({
        disabled: false,
        placeholder: "Select a state",
        allowClear: true,
        data: states_data(loc_data, selectedCountry) //it should delete previous values and update new ones.
    });
}).trigger('change');

If you select USA then USA's states are displayed but if you change it to Australia then Australia's states are shown but USA's are also there, they are not being deleted at all.

What could be the issue?

And how do i remove all choice from State and City if a a user unselects Country field?

Upvotes: 3

Views: 74

Answers (1)

BenG
BenG

Reputation: 15164

A small change to get it working using your code is to .empty() before re-initializing.

.empty() will remove all the options currently in the select then when you re-initializing it will add the new items.

function states_data(loc_data, selectedCountry) {
  var _states_array = [];
  var states = loc_data[selectedCountry];
  for (i = 0; i < states.length; i++) {
    _states_array.push({
      id: states[i],
      text: states[i]
    })
  }
  return _states_array
}

function _cities(state) {
  var val = Math.floor((Math.random() * 100) + 1);
  return [{
    id: val + state,
    text: val + state
  }];
}
var loc_data = {
  'USA': ['USA State 1', 'USA State 2', 'USA State 3'],
  'Australia': ['AUS State 1', 'AUS State 2']
}

$('#loc_state').select2({
  placeholder: "Select a state",
  disabled: true
}).on('change', function() {
  var selectedState = $(this).val();
  $('#loc_city').empty().select2({     // <-- empty first
    disabled: false,
    placeholder: "Select a city",
    allowClear: true,
    data: _cities(selectedState) //it should delete previous values and update new ones.
  });
}).trigger('change');

$('#loc_city').select2({
  placeholder: "Select a city",
  disabled: true
});

var countries_data = [];
for (var key in loc_data) {
  countries_data.push({
    id: key,
    text: key
  });
}

$('#loc_country').select2({
  placeholder: "Select a country",
  allowClear: true,
  data: countries_data
}).on('change', function() {
  var selectedCountry = $(this).val();
  $('#loc_state').empty().select2({        // <-- empty first
    disabled: false,
    placeholder: "Select a state",
    allowClear: true,
    data: states_data(loc_data, selectedCountry) //it should delete previous values and update new ones.
  });
}).trigger('change');
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.full.min.js"></script>

<select id="loc_country"></select>
<select id="loc_state"></select>
<select id="loc_city"></select>

Upvotes: 1

Related Questions