I want persist the 2nd selected options when the first one changes. I've made a jsfiddle to work with it:
http://jsfiddle.net/pmiranda/yeh6b83s/40/
$(document).ready(function() {
// I'll give and empty array, because I will assume that at first is has no data on database
let values = [];
if(1 /* Originally here are some js conditions*/) {
getAL1ByCountry(values);
}
$('#adm_l_1').on('change', function() {
getAL3ByAL1(values);
});
$('#adm_l_1').change();
});
// This functions works with ajax but now I'm just giving some arrays of objects to make the example
function getAL1ByCountry(value) {
let data = {'data': [{'id': 1, 'name': 'Chile'}, {'id': 2, 'name': 'USA'}]};
console.log(data);
$.each(data.data, function (k, v) {
console.log(v);
var _selected = false;
$.each(value, function (k2, v2) {
if (v2.id == v.id) _selected = true;
});
if (_selected)
$('#adm_l_1').append('<option value="' + v.id + '" selected>' + v.name + '</option>');
else
$('#adm_l_1').append('<option value="' + v.id + '">' + v.name + '</option>');
});
$('#adm_l_1').selectpicker('refresh');
$('#adm_l_1').change();
}
function getAL3ByAL1(values) {
$('#adm_l_3').empty();
// Now I will assume that an ajax call was succes and it gives me this data:
/*$.ajax({
url: '/getAL1ByCountry',
method: 'POST',
data: {
country : country_id
}
}).done(function (data) {
*/
let data = {
'data': [
{'id': 1, 'name': 'A'},
{'id': 2, 'name': 'B'},
{'id': 3, 'name': 'C'},
{'id': 4, 'name': 'D'},
{'id': 5, 'name': 'E'},
]
};
$.each(data.data, function (k, v) {
console.log('data', data);
var _selected = false;
$.each(values, function (k2, v2) {
if (v2 == v.id) _selected = true;
});
if (_selected)
$('#adm_l_3').append('<option value="' + v.id + '" selected>' + v.name + '</option>');
else
$('#adm_l_3').append('<option value="' + v.id + '">' + v.name + '</option>');
});
$('#adm_l_3').selectpicker('refresh');
}
My second select change the values from the first one. In the example that's not clear, but the idea is that:
"if I change the values from the first select, don't remove the values from the 2nd one"
There's and empty()
method necesary for this library, because without it it will load this situation each time an option is picked:
(If I pick A) A (If I pick B) AAB (If I pick C) AABABC
etc
Any help?