0

How can i remove duplicates on a multiple select option while maintaining the "selected" attribute.

I have the following in my codes

<select class="colab-select" name="colab[]" multiple>
    <option value="1" selected>Dexter</option>
    <option value="2" selected>James</option>
    <option value="3">Mary</option>
    <option value="1">Dexter</option>
    <option value="2">James</option>
    <option value="3">Mary</option>
</select>

I have these in my jquery for removing the duplicates but when it removes the duplicate, it would "unselect" James but Dexter would still be selected.

var a = new Array();
$(".colab-select").children("option").each(function(x){
    test = false;
    b = a[x] = $(this).val();
    for (i=0;i<a.length-1;i++){
        if (b ==a[i]) test =true;
    }
    if (test) $(this).remove();
});

Any ideas why is this happening?

1 Answers1

2

This example remove duplicate data option in select input:

 $(".colab-select option").each(function (idx, val) {
       $(this).siblings("[value='" + $(this).val() + "']").remove();
  });
son pham
  • 205
  • 1
  • 6
  • yes it does removes duplicate, but it stills "unselect" my options – Dexter Siah Tze Ming Oct 31 '18 at 04:42
  • Please checked again it, I see selected Dexter and James. http://jsfiddle.net/yayTm/103/ – son pham Oct 31 '18 at 05:31
  • Thats odd....mine is just selecting Dexter only...the reason might be because i am using laravel `foreach` loop to display the data and there were some conflicts in between... but i dont see any reason why it would select one option only – Dexter Siah Tze Ming Oct 31 '18 at 05:47
  • 1
    @DexterSiahTzeMing: maybe the laravel framework binds a handler event to select element. If you want to trace the root cause, I think you should list all binddings event and add debug log on that. There are some plugins for chrome or firefox to do that. ref: https://stackoverflow.com/questions/4138543/list-all-bindings-of-an-element-with-jquery – Vu.N Oct 31 '18 at 06:19
  • @Vu.N alright i will give it a try thank you – Dexter Siah Tze Ming Oct 31 '18 at 06:26