Adding table line with javascript does not work onchance event of Buttons

Asked

Viewed 71 times

1

Good morning, I am adding lines from a table (tblformacao) using javascript and on this line I add an input and I am listening to the onchange (.upload) event, however it does not fall in the method. When I change 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) {
   
   });

2 answers

1


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

so that these EventListener also be applied to elements insidos dynamically, you have call the $(".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 inside #tblformacao has the EventListener change associated with them in their creation.

1

Try:

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

Where table refers to the parent element.

Browser other questions tagged

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