从下拉列表中删除重复值

时间:2015-12-22 17:10:37

标签: jquery

我需要从下拉列表中删除重复的值,请告知:

var schoolDropDown = $('#schoolDropDown');
$.ajax({
    type: "POST",
    url: NMUSDDataURL + "API/RequestService.asmx/GetSites",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
        var schools = response.d;
        $('#output').empty();
        $.each(schools, function (index, school) {
            schoolDropDown.append($("<option />").val(school.RecordID).text(school.Schools));
        });
    },

    failure: function (msg) {
        $('#output').text(msg);
    }

});

2 个答案:

答案 0 :(得分:0)

如果sampleArray位于Schools之内,则每次都会创建一个array检查,如果没有,则推入array并附加到列表中。这样就可以删除重复项。

var sampleArray = [];
$.each(schools, function(index, school) {

  // Check if Schools is already in sampleArray
  if (sampleArray.indexOf(school.Schools) == -1) {
    schoolDropDown.append($("<option />").val(school.RecordID).text(school.Schools));
    // Push if unique
    sampleArray.push(school.Schools);
  }
});

我正在检查school.Schools,如果您要检查school.RecordID,那么只需更改我的代码中的属性名称。

答案 1 :(得分:0)

使用临时数组并在循环时将项目存储到它。在添加到您的下拉列表之前,请检查temp数组以查看它是否已添加。如果尚未添加,请将其添加到临时数组并附加到下拉列表。您可以使用$.inArray方法。

var itemsAdded=[];
$.each(schools, function (index, school) {

   if($.inArray(school.RecordID,itemsAdded)===-1) 
   {
      itemsAdded.push(school.RecordID);
      schoolDropDown.append($("<option/>").val(school.RecordID).text(school.Schools));
   }
});

Here是一个工作样本。