Adding table row with javascript does not work buttons onchance event

1

Hello, I'm adding rows from a table (tblformacao) using javascript and in this line I add an input and I'm listening to the onchange (.upload) event, however it does not fall into the method. When I switch to onclick it works. Can anyone tell me what I'm doing wrong?

$('#tblformacao').append('<tr><td>' + option.Text + '</td>' +
                        '' +
                         ' <td>Não</td> ' +
                      '<td> <button class="btn-delete ui-state-default ui-corner-all"      onclick="deletelinha(this)"> ' +
                    ' <span class="icon-remove-sign" /></button> ' +
                       '<input type="file" class="upload" /> ' +
                       ' </td>' +
                         ' <td></td> ' +
                          ' <td></td> ' +
                        '<td style="display:none;">' + $("#CargoId").val() + '</td>' +
                        '</tr>'
);

 $(".upload").on('change', function (e) {
   
   });
    
asked by anonymous 19.02.2016 / 14:49

2 answers

1

Zica, when you use $(".upload").change(function () { ... }) or $(".upload").on("change", function () { ... }) , it applies the event only to elements that already exist on the page.

In order for these EventListener to also be applied to dynamically embedded elements, you must call $(".upload").on("change", function () { ... }) after adding new elements, or use the following (recommended):

$('#tblformacao').on("change", ".upload", function () { ... });

This will make all elements with the ".upload" selector within #tblformacao have the EventListener change associated with them in their creation.

    
19.02.2016 / 15:04
1

Try:

$('table').on('change', '.upload', function(e){
   ...
});

Where table refers to the parent element.

    
19.02.2016 / 15:08