felix manzanas
felix manzanas

Reputation: 119

How to remove html select has duplicate data and text name using jquery?

Is there a way to remove or group the duplicate data and text name of select option in jquery? PLEASE CHECK THIS

Upvotes: 0

Views: 808

Answers (2)

Chandra Kumar
Chandra Kumar

Reputation: 4205

Try use below code to remove duplicate options:

Using .siblings() (to target sibling option elements), and Attribute Equals Selector [attr='']

$("#color option").val(function(idx, val) {
  $(this).siblings("[value='"+ val +"']").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select class ="select-form" name="color" id="color">
  <option value="">Select Color</option>
  <option value="1">Color 1</option>
  <option value="2">Color 2</option>
  <option value="3">Color 3</option>
  <option value="3">Color 3</option> <!-- will be removed since value is duplicate -->
  <option value="2">Color 2</option> <!-- will be removed since value is duplicate -->
</select>

Upvotes: 2

Nathan Patnam
Nathan Patnam

Reputation: 154

I don't know how you are writing the code, but from a high level you could something like along of creating an array that holds every single line of HTML outputed (even duplicates), then create another array and only add unique values to it so there are no duplicates. IE

    var HTML = ["<option>stuff </option>","<option>same stuff </option>","<option> same stuff </option>","<option>different stuff </option>","<option>different stuff </option>","<option>different stuff </option>","<option>different stuff </option>"];
    var uniqueHTML = [];
    $.each(names, function(i, el){
    if($.inArray(el, uniqueHTML) === -1) uniqueHTML.push(el);
});

This will remove any duplicates and leave you array of unique HTML values, which then you could iterate through as output. Not the most time efficient approach, but without providing any code, here is what I can offer.

Upvotes: 0

Related Questions