wowzuzz
wowzuzz

Reputation: 1388

Delete corresponding table row with unique button id

My end goal here is to take a button with a unique id from the index. Based off of the id is clicked (i.e. Which button I click) it deletes that corresponding table row. For example if I hit a delete button with an id of 1..then I want to delete the 1st table row within that table. I am having trouble understanding how I would do this.

Here is my code.

count = ["<TR>", "<TR>", "<TR>", "<TR>"] 

$.each(count, function(index,value) {
    index++;
    $("#deletingRows table").append("<tr><td class='deleteRow' style='font-weight: bold;'>" + 'Row Number: ' + "<input type='text' name='rowNumber' id='rowNumber' style='margin-left: 45px;' value=" + index + ">" + "</input>" + "<input type='button' id='" + index + ' + "name='delete' value='Delete This Row'></input>" + "</td></tr>");
});

Upvotes: 0

Views: 465

Answers (1)

PSL
PSL

Reputation: 123739

You can simplify this to :-

Give class delete to your button.

$('.delete').click(function(){
  $(this).closest('tr').remove(); // closest('tr') will get you its parent tr and call .remove() to remove it.
});

or just use the name itself.

 $('input[name=delete]').click(function(){
     $(this).closest('tr').remove(); // closest('tr') will get you its parent tr and call  .remove() to remove it.
    });

See .closest()

Remember to put the click handler under document.ready.

Upvotes: 1

Related Questions