我试图在下拉列表中显示来自数据库的多个选定的值。我的下拉列表依赖于另一个下拉列表。
我的JS代码是:
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>');
}
});
}
});我在下拉列表中得到了正确的选定值,但是列表中的值是重复的。
我正在使用php编解码器代码数组形式的var cityName = <?= json_encode($cityName); ?>;获取数据库值。

这是console.log(cityName);输出。

我把输出列在下拉列表中。
需要显示单个值。
任何形式的帮助都是受欢迎的,谢谢。
发布于 2018-10-23 07:44:15
现在,您的代码正在输出每个城市的cityName.length时间,因为您正在两个循环中执行append()操作。
如果希望根据城市名称列表中的内容设置所选的多个选项,则只需将检查cityname列表中是否匹配的位与将该选项附加到下拉列表的位分开即可。
逻辑非常简单:
success: function(response) {
$('#city_name').find('option').not(':first').remove();
//loop through each possible option
$.each(response, function(index, data) {
var selected = false; //boolean variable to store whether the option value matches any existing city, or not
//loop through the existing cities
for(var i = 0; i < cityName.length; i++) {
if (cityName[i] == data['city_id_primary']) {
selected = true; //we have a match
break; //no need to carry on checking, so stop the loop
}
}
//now append the option to the dropdown (once!) and set its selected attribute according to the value of the "selected" boolean.
$('#city_name').append('<option value="' +data['city_id_primary']+ '" ' +(selected === true ? 'selected' : '')+ '>' +data['city_name']+ '</option>');
});
}使用一些jQuery数组函数可能有一种“更整洁”的编写方法,但这是最简单的理解版本。
发布于 2018-10-23 04:30:51
两个函子的变化逻辑:
for (var i = 0; i < cityName.length; i++) {
$.each(response, function (index, data) {
$('#city_name').append('<option value="' + data['city_id_primary'] + '" ' + (cityName[i] == data['city_id_primary'] ? ' selected ' : '') + '>' + data['city_name'] + '</option>');
});
}https://stackoverflow.com/questions/52941097
复制相似问题