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

Asked

Viewed 1,197 times

3

I know it’s possible to take the value of a select selected with:

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

But I was wondering if it’s possible to catch some select is selected via event, for example when selecting a option, trigger some function.

I think it would look something like:

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

});

Or:

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

});

But until then I couldn’t make it work.

  • It is not clear what you want to do. You would like to define a different function for each value of select and, when selecting, perform the function corresponding to the selected value?

  • I intend for the user to select from an option, fire something, it need not be different

2 answers

3


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

$("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>
  <option value="um">Um</option>
  <option value="dois">Dois</option>
  <option value="tres">Três</option>
</select>

  • Yeah I thought about the change, I thought it wouldn’t work but I’ve got an idea here that’s gonna make it right

1

Following is an example where you can define different actions for each option of select user-selected.

$('#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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.