简体   繁体   中英

Delete row from table on corresponding delete button click

I'm facing some problem in the given example. I have a list of three items, all of them have a delete button, when I click on delete button the corresponding row is deleted. It's works fine.

Now my problem is if I have all three item in the list and I want to delete only first item and I click on first delete button it removes all the rows of the table.

Demo Here

That's because your first id is 0 so its deleting all elements, remove the if condition and else block it works fine, if you want to delete entire table then add other button.

$('input[type=button]').click(function () {
    $(this).closest("tr").remove();
});

Working Fiddle

There is one basic flaw in your Code.

You were binding on click to just button tag, but in your HTML there were no button tags, there were input tags with button type.

After this you are creating a variable called "id" which is unnecessary in this case. With jQquery you do not need this.

Using the following line of code takes care of everything. So simplify life and make this the jQuery as short as possible.

$(this).parent().parent().remove();

As far as you #divGrid being empty is a false statement as the div will never be empty unless you remove the entire #myTable child element

You can do that by using the following condition

if( $('#divGrid ').is(':empty') ) {
   $('#divGrid').html("All item removed");
}

Here is the solution with just 3 lines of jQuery that you really need.

EDIT: Here is a fiddle to check the rows being empty and if empty then the table will be replaced by the text "All items removed"

Working Fiddle

try this

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

Demo http://jsfiddle.net/BLV2g/14/

to be more safer the button will not delete else where

$('#myTable :button').click(function() {  
    $(this).closest("tr").remove();
});

Try this,

function delSpec(rl)
  {    
     r=document.getElementById("insSpecc").rows.length;
     if(r!=2){
       document.getElementById("insSpecc").deleteRow(r-1)
     }
  }

Demo http://jsfiddle.net/nKkhW/111/

I guess this is what you want to do:

$('#myTable :button').click(function () {
  $(this).parent().parent().remove();
  var rowCount = $('#myTable tr').length;
  if (rowCount == 1) {
    $('#divGrid').empty();
    $('#divGrid').html("All item removed");
  }
});

The logic behind is:

  1. whenever an input type button is clicked, trigger the jquery event.
  2. remove the tr content where the button is in.
  3. check if there are rows except the title row, if only title row, replace the title.

Demo

由于第一个删除按钮的ID为del0 ,它将进入else子句并删除所有三行。

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