I'm trying to delete a table row using jQuery. I used all the methods I could find and none work. I have a delete on the end of each row and when I click it I trigger a function which should delete the row where it is located. But it just won't work.
In the comments are my tries which failed. Is there a pseudo like first but for the current item (something like this) ?
function del(){
//$(this).parent().parent().remove();
//$(this).closest("tr").remove();
//$('table tr:last').remove(); this one worked but it deletes the last and I want the current one to be deleted
}
Here is the code that generates the table:
$.getJSON("nutritional_value.php?value=" + encodeURI(value), function (data) {
var ttr = $("<tr class='rou' />");
$.each(data, function(k, v){
var store_1 = v * (parseFloat(uneseno, 10) / 100);
var xstore_1 = store_1.toFixed(2);
$("<td class='teedee'></td>").text(k=='name' ? v : xstore_1).appendTo(ttr);
});
$("<td id='delete' onClick='del();'>Delete</td>").appendTo(ttr);
$("#tejbl").append(ttr);
});
$(this).closest("tr").remove();
will work just fine if you change the HTML to use onClick='del(this);'
. Even better would be to skip the ugly DOM0 event binding and use .on()
:
$(document).on('click', 'td.delete', del);
Note that your code is currently generating HTML with duplicate IDs, which is bad-bad-bad. Element IDs must be unique. Use classes instead:
$("<td class='delete'>Delete</td>").appendTo(ttr);