1

I want to delete a row when i click the glyphicon-trash. I tried many ways but still cant get row index properly.

<table class="table table-bordered" id="table_GemList">
<thead>
  <col style="width: 25%">
  <col style="width: 25%">
  <col style="width: 25%">
  <col style="width: 25%">
</thead>
<tbody id="GemListBody">
<tr>
  <td>Oval</td>
  <td>Red</td>
  <td>2.23</td>
  <td><span class="glyphicon glyphicon-trash"></span></td>
</tr>
<tr>
  <td>Box</td>
  <td>Pink</td>
  <td>2.23</td>
  <td><span class="glyphicon glyphicon-trash"></span></td>
</tr>
</tbody>
</table>

---------- My code

 $(document).on("click", ".glyphicon-trash", function () {

        var d = $(this).parentNode.parentNode.rowIndex;
        document.getElementById("table_GemList").deleteRow(d);

});

5 Answers 5

3

$(this) returns a jQuery object. You can't directly read the properties of the collection's items that way. In fact you shouldn't wrap the element with the jQuery constructor as you don't want to use the jQuery APIs.

var d = this.parentNode.parentNode.rowIndex;

Since you are using jQuery, you can simply use the closest and remove methods.

$(this).closest('tr').remove();
Sign up to request clarification or add additional context in comments.

Comments

2

You need to update

var d = $(this).parentNode.parentNode.rowIndex;
document.getElementById("table_GemList").deleteRow(d);

to

$(this).closest("tr").remove();

For reference on closest() - https://api.jquery.com/closest/

For reference on remove() - https://api.jquery.com/remove/

Comments

0

Maybe this helps....

 $(document).on("click", ".glyphicon-trash", function ()
 {
     $(this).closest("tr").remove(); // remove row
 });

Comments

0

This should works.

$(document).on("click", ".glyphicon-trash", function () {
  $(this).parents('tr:first').remove();
});

Comments

0

you can simply delete the parent in which trash icons is there by below jquery code

 $(document).on("click", ".glyphicon-trash", function (){
 $(this).parent().parent().remove(); // remove row

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.