jquery – Running a script through the 'name' attribute doesn't work

Question:

Follow 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 selected item is changed:

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

However, through the name attribute I can't execute. If I use the ID attribute, it works! Here's an example:

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

In this way, Alert runs smoothly. And yes, I could use the ID attribute, but many times 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 run.

Answer:

Your selector is looking for an input , it should be looking for a select . In addition, two observations:

  • if you have several select , give them the same class and use $(".form-control").on( , so they will all be selected
  • use quotes in 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>
Scroll to Top