Alexander Kim
Alexander Kim

Reputation: 18382

2 identical select list, but don't allow the same values selected in them

Here i have the javascript code for my task: https://jsfiddle.net/gckkvLcv/4/

<select id="s1">
  <option selected="selected">USD</option>
  <option>KZT</option>
  <option>EUR</option>
</select>
<select id="s2">
  <option>USD</option>
  <option selected="selected">KZT</option>
  <option>EUR</option>
</select>
  1. I need to translate it to a jQuery version.
  2. On a document load i can see the same values in a select lists. I need to disable that behavior.

Upvotes: 0

Views: 70

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Since you're using jQuery that could be done simply like :

$('.tracked_select').on('change', function() {
    //Get selected options
    var selected_options = $('.tracked_select').map(function(){
      return this.value
    }).get();

    //Disable the already selected options and enable others
    $('.tracked_select option').each(function(index) {
      $(this).prop('disabled', $.inArray($(this).val(), selected_options) != -1);
    });
});

Hope this helps.

trigger_chane();

$('.tracked_select').on('change', function() {
  trigger_chane();
});

function trigger_chane(){
  var selected_options = $('.tracked_select').map(function(){
    return this.value
  }).get();

  $('.tracked_select option').each(function(index) {
    $(this).prop('disabled', $.inArray($(this).val(), selected_options) != -1);
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select class="tracked_select">
  <option selected="selected">USD</option>
  <option>KZT</option>
  <option>EUR</option>
</select>
<select class="tracked_select">
  <option>USD</option>
  <option selected="selected">KZT</option>
  <option>EUR</option>
</select>

Upvotes: 1

Related Questions