Search code examples
jquerydelete-row

jQuery delete table row by dynamic id


I have the following code

<div>
    <input type="text" maxlength="20" id="nameText"></input>
    <button type="button" id="add">Add</button>
</div>
<div>
    <table id="form">
        <tbody>
            <tr>
                <th>Name</th>
                <th>Delete</th>
            </tr>
        </tbody>
    </table>
</div>

The jQuery part

var rowNum = 0;

$('#add').click(function() {
    var name = $('#nameText').val();
    rowNum ++;
    var row = '<tr id="row' + rowNum + '">'
            + '<td>' + name 
            + '<button type="button" id="deleteRow' + rowNum + '">Delete</button>'
            + '</td>'
            + '</tr>';

    $(row).insertAfter($("#form > tbody > tr:last"));
    $('#deleteRow' + rowNum).click(function () {
        $('#row' + rowNum).remove();
    });
});

This will dynamically add table rows when you click "Add" button, and I want to delete row by id, but it only delete the last row, how can I fix it?

jsfiddle: http://jsfiddle.net/sgs603cm/


Solution

  • Don't use incremental id attributes - they quickly become a pain to maintain.

    Instead, use a single common delegated event handler based on a class selector, and use the this keyword to refer to the element that raised the event. Try this:

    $('#add').click(function() {
        var name = $('#nameText').val();
        rowNum ++;
        var row = '<tr id="row' + rowNum + '">'
                + '<td>' + name 
                + '<button type="button" class="delete">Delete</button>'
                + '</td>'
                + '</tr>';
    
        $(row).insertAfter($("#form > tbody > tr:last"));
    });
    
    $('#form').on('click', '.delete', function (e) {
        e.preventDefault();
        $(this).closest('tr').remove();
    });