Selector this + option

1

I am trying that when the Change event is launched in a select with the same class as others, the value is retrieved, and if it is equal to one data then select another of the same select. My problem is in, I do not know how to create the selector. I've tried like this, but it does not work. Welcome all the answers

$(function(){

  $(document).on('change','.sel',function(){
    var val = parseInt( $(this).val() );
    if( val === 2 ){
      $(this + 'option[value="3"]').prop('selected',true);
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

<select class="sel">
  <option value="1">Valor 1</option>
  <option value="2">Valor 2</option>
  <option value="3">Valor 3</option>
</select>
    
asked by Alberto Siurob 23.02.2018 в 23:20
source

1 answer

2

The problem is that this is an object (in particular the class select .sel ) and you can not simply put it in a selector by concatenating it with another one string. The best option I can think of is to use .find to look for the option within the object. It would be a simple change:

$(this + 'option[value="3"]')

for

$(this).find('option[value="3"]')

And it will work for you:

$(function(){

  $(document).on('change','.sel',function(){
    var val = parseInt( $(this).val() );
    if( val === 2 ){
      $(this).find('option[value="3"]').prop('selected',true);
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

<select class="sel">
  <option value="1">Valor 1</option>
  <option value="2">Valor 2</option>
  <option value="3">Valor 3</option>
</select>
    
answered by 23.02.2018 / 23:26
source