dunfa
dunfa

Reputation: 539

Cannot remove() a row append() to a table

I have a table with several rows () and I use jQuery append() to add one more row to the table. Then I try to delete that row with remove(), which is working fine with the original rows, and fail.

Please help. Thanks.

<table id="mybbbb" border="1" style="width:300px"><tbody>
    <tr><td>some text</td><td><div class="linksd">delete</div></td></tr>
    <tr><td>some text</td><td><div class="linksd">delete</div></td></tr>
    <tr><td>some text</td><td><div class="linksd">delete</div></td></tr>
    <tr><td>some text</td><td><div class="linksd">delete</div></td></tr>
</tbody></table>

<div id="addRow">add row</div>

<script>
jQuery("#addRow").click(function(event){
    event.preventDefault();
    jQuery("#mybbbb > tbody:last").append("<tr><td>more text</td><td><div class='linksd'>delete</div></td></tr>");
});

jQuery(".linksd").click(function(event){
            event.preventDefault();
            jQuery(this).parent().parent().remove();
            return false;
});
</script>

Upvotes: 0

Views: 585

Answers (2)

Iswanto San
Iswanto San

Reputation: 18569

There is no default behaviour for clicking on a div.

Remove event.preventDefault(); and return false from your code like this, works for me.

jQuery(".linksd").click(function(event){   
    jQuery(this).parent().parent().remove();   
});

Demo : jsfiddle

Upvotes: -1

scrowler
scrowler

Reputation: 24406

Your problem is that the newly created rows are not present in the DOM when the Javascript event listeners are assigned.

For jQuery 1.6 (as used in your fiddle) you can use live to listen past the original DOM creation point:

$('.linksd').live('click', function(event){

And for more modern versions of jQuery (live is deprecated now) you should use the on delegation:

$(document).on('click', '.linksd', function(event){

Examples in the fixed fiddle and change the jQuery version to see.

Upvotes: 3

Related Questions