It is possible to know that an option was selected in javascript event

2

I know that it is possible to get the value of a select selected with:

$("id option:selected").val()

But I wanted to know if it's possible to catch when any of this select is selected via an event, such as selecting a option , triggering a function.

I think it would look something like this:

$("#ProcessoId").on('select', function () {
    alert("ooi");

});

Or:

$("#ProcessoId").on('selected', function () {
    alert("ooi");

});

But until then I could not make it work.

    
asked by anonymous 24.08.2018 / 15:47

2 answers

3

What you're looking for is the jQuery change event:

$("select").on("change", function() {
  var valor = $(this).val();   // aqui vc pega cada valor selecionado com o this
  alert("evento disparado e o valor é: " + valor);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><select><optionvalue="um">Um</option>
  <option value="dois">Dois</option>
  <option value="tres">Três</option>
</select>
    
24.08.2018 / 15:52
1

Here is an example where you can define different actions for each option of select selected by the user.

$('#marca').change(function() {
  var marca = $('#marca').val();
  switch (marca) {
    case '':
      alert ("Selecione uma marca!")
      break;
    case 'VW':
      alert ("Selecionou Volkswagen")
      break;
    case 'GM':
      alert ("Selecionou Chevrolet")
      break;
    case 'FIAT':
      alert ("Selecionou FIAT")
      break;
    default:
      alert ("Selecione uma marca!")
      break;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select name='marca' id='marca' required>
  <option value=''>Selecione a marca</option>
  <option value='VW'>Volkswagen</option>
  <option value='GM'>Chevrolet</option>
  <option value='FIAT'>FIAT</option>
</select>
    
24.08.2018 / 15:55