如何删除下拉列表中的重复项

时间:2018-12-25 20:21:30

标签: jquery unique dropdown

我尝试从下拉列表中删除重复项,正在处理的数据已损坏,因此我需要在前端的下拉列表中将其删除。

$(document).ready(function () {
   var usedNames = {};
   $("#myDropdown").each(RemovingFunction(usedNames));
});


function RemovingFunction (usedNamesObject){
  if (usedNamesObject[this.value]) {
    $(this).remove();
  } else {
    usedNamesObject[this.value] = this.text;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="myDropdown">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="mercedes">Mercedes</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
  <option value="audi">Audi</option>
  <option value="audi">Audi</option>
</select>

我不知道如何使RemoveFunction起作用,请帮忙,我需要使此函数成为全局函数,以便在其他下拉菜单中起作用

2 个答案:

答案 0 :(得分:1)

使用.siblings()(以同级选项元素为目标)和属性等于选择器[attr =“”]

$(".select option").val(function(idx, val) {
  $(this).siblings('[value="'+ val +'"]').remove();
});
<select class="select">
  <option value="">All</option>
  <option value="com">.com 1</option>
  <option value="net">.net 1</option>
  <option value="com">.com 2</option> <!-- will be removed since value is duplicate -->
  <option value="net">.net 2</option> <!-- will be removed since value is duplicate -->
</select>

答案 1 :(得分:-1)

您可以使用对象的键是唯一的事实来删除所有重复项。

//for an object objOpt you can iterate  all the elements like so:  
objOpt[ elementHTML ] = domElement
//of you have 10 similar element, in the end only one makes it to the object

$(function() {
    var select = $('#myDropdown');
    var objOpt = {};
    select.find('option').each(function() {
        objOpt[this.outerHTML] = this;
    });
    select.empty();
    for(key in objOpt) {
        select.append( objOpt[key] );
    };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="myDropdown">
          <option value="volvo">Volvo</option>
          <option value="saab">Saab</option>
          <option value="mercedes">Mercedes</option>
           <option value="mercedes">Mercedes</option>
            <option value="mercedes">Mercedes</option>
          <option value="audi">Audi</option>
          <option value="audi">Audi</option>
          <option value="audi">Audi</option>
       </select>