0

I've got a table that I can't seem to delete the rows from no matter what I try. Its a simple table of 5 columns and a few rows generated from a php/mysql lookup using Json. I'd eventually like to delete the row from the mysql table with the button click but I'm stuck with the "easy" part of deleting the row in jquery.

Here is the code to create my table:

var table = $('<table></table>').addClass('tbc');
for (var i = 0; i < json.admin_tables.length; i++) {
var row = $('<tr></tr>').addClass('guid').attr('id', i).add('<td>' + json.admin_tables[i].Room + '</td><td>' + json.admin_tables[i].time + '</td><td>' + json.admin_tables[i].Desk + '</td><td>' + i + '</td><td><input type="button" id="'+ i + '" class="delete" value="Delete row ' + i + '"</td>');
table.append(row);
$('#roomTable').append(table);
} 

The following code does nothing at all however (no errors in firebug)

$('.delete').click(function() { 
    $(this).closest("tr").remove();
}

Changing "tr" to "td" will delete the button only and I don't want to have to delete every field individually!

1 Answer 1

2

The .delete elements are inserted dynamically, so you'll need delegated event handlers to target them:

$('#roomTable').on('click', '.delete', function() { 
    $(this).closest("tr").remove();
});
Sign up to request clarification or add additional context in comments.

8 Comments

nope adeneo doesn't do anything at all for me. I tried the empty() as well just to be sure. You can see it here: examtime.atwebpages.com/admintable.php
if you are using older jquery may need api.jquery.com/delegate instead of on. @adeneo thinking more on it i think it is just a speed thing. the remove was taking to long and by emptying it first it got faster for some reason.
I did try a few versions with delegate and live as well. I'm using 1.8.2 so not too old anyway
i did notice your doctype is invalid, think there is a typo in it. not sure if that makes a difference.
@user1569869 - Your markup is invalid, the .delete elements are'nt children of the tr's, so there is no closest('tr') to remove. The errors originates from using add() and not append() when appending the td's to the tr's.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.