Running a script through the 'name' attribute does not work

5

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 you change the selected item:

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

However, through the name attribute I can not 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'm tired of creating an ID just to execute a code. I want to understand why not run.

    
asked by anonymous 17.04.2017 / 15:26

2 answers

6

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

  • If you have multiple select , give them the same class and use $(".form-control").on( , so they will all be selected
  • uses 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><selectclass="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>
    
17.04.2017 / 15:33
5

The element is not a input but a select , in jquery there are several types of selectors , in the example below I used name*='dd_medidaAplicada' , that is, any select item containing dd_medidaAplicada in 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><selectclass="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>
    
17.04.2017 / 15:33