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>
$("loc_state").empty();,但无法猜测它是否也可以用于绑定事件。谢谢! - Jon L