click () does not recognize button dynamically inserted inside tr

1

I dynamically insert items 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>"

Then, when I click on the button (inserted in the table using the function) I get no return.

Function used for button interaction:

$("table#tb-itens tbody tr button[type=button]").click(function (){
    alert(this.value);
});
    
asked by anonymous 09.05.2017 / 22:22

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 added benefit of being able to process events from descending elements added to the document later.

    
09.05.2017 / 22:24