I am attempting to display multiple selected values in a dropdown list that are coming from a database. The contents of my dropdown list are dependent on another dropdown list.
Here is the JS code I am using:
var cityName = <?= json_encode($cityName); ?>;
var area_name = document.getElementById('area_name').value;
$.ajax({
'url': '<?= base_url('utility/cityByArea'); ?>',
'type': 'POST',
'dataType': 'JSON',
'data': {
area_name : area_name
},
success: function(response) {
$('#city_name').find('option').not(':first').remove();
$.each(response, function(index, data) {
for(var i = 0; i < cityName.length; i++) {
$('#city_name').append('<option value="' +data['city_id_primary']+ '" ' +(cityName[i] == data['city_id_primary'] ? 'selected' : '')+ '>' +data['city_name']+ '</option>');
}
});
}
});
Although I am able to get the correct selected values in the dropdown list, the values are being repeated.
To retrieve the database value, I am using PHP CodeIgniter code
var cityName = <?= json_encode($cityName); ?>;
which stores the values in an array.
https://i.sstatic.net/f6UfL.png
Displayed above is the output of console.log(cityName);
.
https://i.sstatic.net/eeoGX.png
I am successfully displaying the output in the dropdown list.
However, I need assistance in showing single values only.
I would appreciate any kind of help. Thank you in advance.