Search code examples
jqueryhtmlhtml-tablerow

How to catch click event with jQuery, on dynamically created button


I have HTML table where I can create dynamically new rows. With every row, I also create a button which I can delete the row that have just created. But jQuery does not capture the event in rows created dynamically. HTML code:

<table>
...
<tbody id="nuevo_producto">
    <tr id="1">
        <td><input type = "hidden" name = "tabla-1">1</td>
        <td><input readonly="readonly" class = "form-control" placeholder = "Ref." type = "text" size = "15" id = "modelo_ref_1" name = "modelo_ref_1" value="122"></td>
        <td><input class = "form-control" placeholder = "Ref. C" type = "text" size = "15" id = "modelo_refc_1" name = "modelo_refc_1" value="231"></td>
        <td><input class = "form-control" placeholder = "Modelo" type = "text" size = "60" id = "modelo_modelo_1" name = "modelo_modelo_1" value="sadsadsad"></td>
        <td><input class = "form-control" placeholder = "PVP" type = "text" size = "15" id = "modelo_pvp_1" name = "modelo_pvp_1" value="12"></td>
        <td><button class="btn btn-default delete_row" id="1" value="eliminar_fila"><span class="glyphicon glyphicon-minus"></span></button></td> <!-- Button to delete row -->
    </tr>
    <tr id="2">
    ... <!--another rows that I have created dinamically-->
    </tr>
    ...
</tbody>
</table>

jQuery code to delete the row that have just clicked

$(".delete_row").each(function() {
    $(this).on("click", function(e) {
        e.preventDefault();
        $("tr#" + $(this).attr("id")).remove();
    });
});

The problem is that event button only works with existing rows. If I create a new row, the 'on click' event does not work.


Solution

  • You need to use Event Delegation

    $('#nuevo_producto').on('click','.delete_row',function(){
        $("tr#" + $(this).attr("id")).remove();
    });
    

    .on()


    Two HTML elements with same id attribute: How bad is it really?

    Id must be unique


    Change your html

    <tr id="1">
    

    to

    <tr data-id="1">
    

    Than use

    $('#nuevo_producto').on('click','.delete_row',function(){
        $('tr[data-id="'+$(this).data('id')+'"]').remove();
    });
    


    or

    Change

    <button class="btn btn-default delete_row" id="1"
    

    to

    <button class="btn btn-default delete_row" data-id="1"
    

    Than use

    $('#nuevo_producto').on('click','.delete_row',function(){
        $('#'+$(this).data('id')).remove();
    });
    

    .data()