noobcoderiam noobcoderiam - 3 years ago 139
CSS Question

Creating a To-Do list with Jquery, can't delete dynamically added Table Rows by clicking a button

So I have code that takes the input from a text box and adds it to the to do lsit body which is a table element. Each input added creates a new tr that has the value entered into the box and appears with an inline button beside it.

Before I added the buttons, my on click function to remove the TR worked. Now that I am trying to use the buttons to delete the tr on click, it either does nothing or deletes the button but keeps the tr and it's text.

$('input').keypress(function(event){
var x = $('input:first').val();
if(event.which === 13){
$('#listTable').append('<tr class= "listItem"><td><button type="button" class="btn btn-default deleteButton" aria-label="Left Align"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button>'+x+'</td></tr>')//adds a new tr with the input from the box and prints it in the td of the tr
$('input').val("");
}
$('.deleteButton').on('click', function(){
$(this).remove();
});
});

Answer Source

Try

$('#listTable').on('click', '.deleteButton' , function(){
 alert('remove');
 $(this).parent().remove();
});

Instead of

$('.deleteButton').on('click', function(){
   $(this).remove();
});  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download