Delete options from different select

2

I have 3 selects , I want that when one is chosen, it is deleted from the other 2 but without deleting the first one. Is it possible?

<select class="sel">
  <option value="1"></option>
  <option value="2"></option>
  <option value="3"></option>
</select>

<select class="sel">
  <option value="1"></option>
  <option value="2"></option>
  <option value="3"></option>
</select>

<select class="sel">
  <option value="1"></option>
  <option value="2"></option>
  <option value="3"></option>
</select>
<script>
    $(document).on('change','.sel',function(){
      var opcion = $(this).val();
      $('.sel').each(function(){
          $('.sel option[value="'+opcion+'"]').remove();
      })
    });
</script>

It is eliminating the value of the SELECT from where I took it. How can I prevent that?

    
asked by Alberto Siurob 12.01.2017 в 22:09
source

1 answer

2

Modify your script leaving it this way:

$(document).on('change','.sel',function(){
  $(this).siblings().find('option[value="'+$(this).val()+'"]').remove();
});

What it does is:

  • Of the select of any that would be searched for the sibling elements to find the sibling elements use .siblings() which makes me search for all select
  • Then I look for the options with .find() in which I tell it that it will search for the element that contains the selected value of the select that changes and remains this way .find('option[value="'+$(this).val()+'"]')
  • I remove that element from selects with .remove()
  • $(document).on('change','.sel',function(){
      $(this).siblings().find('option[value="'+$(this).val()+'"]').remove();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select class="sel">
      <option>Selecciona</option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    
    <select class="sel">
      <option>Selecciona</option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    
    <select class="sel">
      <option>Selecciona</option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
        
    answered by 12.01.2017 / 22:37
    source