在JavaScript AJAX响应的下拉列表中获取重复的值

时间:2018-10-23 04:15:06

标签: javascript ajax codeigniter-3

我正尝试在来自数据库的下拉列表中显示多个选定的值。我的下拉列表依赖于另一个下拉列表。

我的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 codeigniter代码var cityName = <?= json_encode($cityName); ?>;获取数据库值。

enter image description here

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

enter image description here

我在下拉列表中得到输出。

需要显示单个值。

欢迎您提供任何帮助。

2 个答案:

答案 0 :(得分:1)

现在,由于您在两个循环中都执行append()操作,因此您的代码正在cityName.length的每个城市中输出。

如果要根据城市名称列表中的内容设置多个选项,则只需将检查城市名称列表中匹配项的位与将选项附加到的位分开即可下拉菜单。

逻辑很简单:

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>');
    });
  }

P.S。使用某些jQuery数组函数可能会采用一种“更整洁”的方式编写代码,但这是最容易理解的版本。

答案 1 :(得分:-2)

更改每个功能2个的逻辑:

hn-1