简体   繁体   中英

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();
    });     
}); 

Try

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

Instead of

$('.deleteButton').on('click', function(){
   $(this).remove();
});  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM