Paul Maudry
Paul Maudry

Reputation: 7

Remove duplicate option from select (with multiple select on the same page) jQuery

Below is my jQuery code. It works for the first select of the page but not the others. The other select's options are removed and I can't figure out why.

Here is the link to one of the concerned page (click on the big blocks to see the dropdown): my website

Thanks in advance for the time spent on my issue.

var city = {};

$('.ville-select option').each(function() {
  var val = $(this).val();
  if (city[val]) {
    $(this).remove();
    return;
  }
  city[val] = 1;
});

Upvotes: 0

Views: 714

Answers (1)

Chitrang
Chitrang

Reputation: 2114

Since you have more than one select on the same page, you would need to iterate through each of them to process duplicate options:

// Iterate through each select boxes
$('.ville-select').each(function() {
  var city = {};
  $(this).find('option').each(function() {
    var val = $(this).val();

    if (city[val]) {
      $(this).remove();
      return;
    }

    city[val] = 1;
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="ville-select">
  <option value="a">a</option>
  <option value="b">b</option>
  <option value="a">a</option>
</select>
<select class="ville-select">
  <option value="a">a</option>
  <option value="b">b</option>
</select>

Upvotes: 1

Related Questions