jQuery append and binding click event using on

MatthewLee picture MatthewLee · Oct 9, 2013 · Viewed 8.6k times · Source

I am attempting to create a table row with a button in it that when clicked creates a new table row. The new row also has the same "add line" button on it and I would like to be able to click that button to add another row. But I cannot seem to get the click event to bind to an element that is appended within the click event. I am sure I am using "on" incorrectly but I can't seem to figure out how to do this.

http://jsfiddle.net/vivojack/WkfvC/2/

my (simplified) html

<table id="ct">
    <tbody>
    <tr id="list_items_11" class="list_item">
        <td>This Line</td>
        <td><input type="button" name="addNewArea" class="addNewArea button" value="+"></td>
      </tr>
   </tbody>
</table>

my (simplified) javascript

$('#ct tbody tr td').on('click', '.addNewArea', function(event) {   
    var areaCount = $('#ct tbody tr').length;
    var newAreaLine = '<tr id="list_items_' + areaCount + '" class="list_item"><td>New Line</td><td><input type="button" name="addNewArea" class="addNewArea button" value="+" /></td></tr>';
    $(newAreaLine).appendTo('#ct tbody');
    $(this).remove();
});

Thanks in advance.

Answer

Jason P picture Jason P · Oct 9, 2013

You have to bind the handler to an element that isn't dynamic. You're attempting to bind to the td, which doesn't exist when you do the binding. You can bind to the table instead:

http://jsfiddle.net/TMvN6/

$('#ct').on('click', '.addNewArea', function(event) {