1
votes

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

6

6 Answers

4
votes

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

3
votes

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

1
votes

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

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

0
votes

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/

-1
votes

Since first delete button id is del0 it will go to the else clause and delete all the three rows.