click() does not recognize button inserted dynamically inside tr

Asked

Viewed 103 times

1

Insert items dynamically into a table using the following function:

$("#inserir-item").click(function (){
    ...
    $("table#tb-itens tbody" ).append(retorno);
}

The return variable contains something like:

"<tr id="tr-22-2222" align="center">
    <td>22-2222</td>
    <td align="left">Descrição IV</td>
    <td>4</td>
    <td>
        <button type="button" value="22-2222" class="btn btn-primary">X</button>
    </td>
</tr>"

Soon after, when clicking the button (inserted in the table using the mecionada function) I get no return.

Function used for button interaction:

$("table#tb-itens tbody tr button[type=button]").click(function (){
    alert(this.value);
});

1 answer

4


You can use:

$(document).on("click", "table#tb-itens tbody tr button[type=button]", function (){
    alert($(this).val());
});

That way, using delegated events, there is the advantage of being able to process events of descending elements added to the document later.

  • Hello Lucas Costa, could complement the answer explaining why?

  • Sure, reply edited @luccasrodrigo

Browser other questions tagged

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