Running a script through the name attribute does not work

Asked

Viewed 54 times

5

Follows the code:

<select class="form-control" name="dd_medidaAplicada" id="dd_medidaAplicada">
<option value="0"></option>
<option value="cancelada">Advertência Cancelada</option>
<option value="escrita">Advertência Escrita</option>
<option value="verbal">Advertência Verbal</option>
<option value="dispensa">Dispensa por Justa Causa</option>
<option value="suspensao">Suspensão</option>

I want to run a script every time it is changed from selected item:

$("input[name=dd_medidaAplicada]").on('change', function() { alert( this.value );})

However, through the attribute name I cannot execute. If I use the attribute ID, it works! Follow example:

$("#dd_medidaAplicada").on('change', function() { alert( this.value );})

This way, Alert runs smoothly. And yes, I could use the ID attribute, but often this same problem happens in my codes and I got tired of creating an ID just to execute a code. I want to understand why not.

2 answers

6


Your dial is looking for a input, should be looking for a select. In addition, two comments:

  • if you have several select, gives them the same class and uses $(".form-control").on(, so all will be selected
  • uses quotes on selectors, select[name='dd_medidaAplicada']

$("select[name='dd_medidaAplicada']").on('change', function() {
  console.log(this.value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select class="form-control" name="dd_medidaAplicada" id="dd_medidaAplicada">
    <option value="0"></option>
    <option value="cancelada">Advertência Cancelada</option>
    <option value="escrita">Advertência Escrita</option>
    <option value="verbal">Advertência Verbal</option>
    <option value="dispensa">Dispensa por Justa Causa</option>
    <option value="suspensao">Suspensão</option>
</select>

  • 1

    It worked perfectly. Thank you!

5

The element is not a input and yes a select, in jquery there are several types of selectors, in the example below I used name*='dd_medidaAplicada', that is, any select item that contains dd_medidaAplicada in the name.

$("select[name*='dd_medidaAplicada']").on('change', function() {
  alert(this.value);
})
//$("#dd_medidaAplicada").on('change', function() { alert( this.value );})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" name="dd_medidaAplicada" id="dd_medidaAplicada">
<option value="0"></option>
<option value="cancelada">Advertência Cancelada</option>
<option value="escrita">Advertência Escrita</option>
<option value="verbal">Advertência Verbal</option>
<option value="dispensa">Dispensa por Justa Causa</option>
<option value="suspensao">Suspensão</option>

  • Only the quotes are missing on the dial.

  • @Renan corrected, thanks!

  • Thanks for the explanation!

Browser other questions tagged

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