Check if select option class already exists

I want to append a select element dynamically in html and when any option is changed in any of the select then I want to check if that option is already selected in any of the existing select elements.

For that I am using a class for each select option and when an option is changed in any select, then check if that class of selected option exists already.

I’m using following code but I’m unable to figure out how to check each select to see if the same option is selected.

HTML:

<div class="list">

</div>

<div class="hide">
  <select>
    <option value=""></option>
    <option class="a" value="">A</option>
    <option class="b" value="">B</option>
    <option class="c" value="">C</option>
    <option class="d" value="">D</option>
  </select>
</div>

 <button class="add" type="add">Add</button> 

Js:

$('.add').on('click', function(e){
    $('.list').append($('.hide').html());

});


$(document).on('change', '.list select', function(){

var cls = $(this).find(':selected').attr('class');

if ($('.list .'+cls).length > 0) {
    alert('It exists');
}


});

JSFiddle: http://jsfiddle.net/vtzor9Ld/

Answer

Your code could be fixed with this line:

if ($(`.list option.${cls}:selected`).length > 1) {
    console.log('It exists');
}

You’ll want to test for more than 1 occurrence, (rather than 0), and you’ll want to test the selected options only for matching class

Here’s another method that finds the occurrences one by one in case that was useful information.

$('.add').on('click', function(e) {
  $('.list').append($('.hide').html());
});

$(document).on('change', '.list select', function() {
  var cls = $(this).find(':selected').attr('class');
  $('.list select').not($(this)).find('option:selected').each(function(i) {
    if ($(this).hasClass(cls)) console.log("Matching class on select # " + (i + 1))
  })
});
.hide {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list"></div>
<div class="hide">
  <select>
    <option value=""></option>
    <option class="a" value="">A</option>
    <option class="b" value="">B</option>
    <option class="c" value="">C</option>
    <option class="d" value="">D</option>
  </select>
</div> <button class="add" type="add">Add</button>