Friday, 4 August 2017

Delete HTML Table Row Using Javascript/JQuery Without RowIndex

Using JavaScript:

<!DOCTYPE html>
<html>
<head>
<style>
table, td {
    border: 1px solid black;
}
</style>
</head>
<body>

<p>Click the button to delete the any row from the table.</p>

<table id="table1">
  <tr id="myRow1">
    <td>First cell</td>
    <td>Second cell</td>
    <td>Third cell</td>
    <td><input type="button" onclick="deleteRow('myRow1')" value="Delete"/></td>
  </tr>
  <tr id="myRow2">
    <td>First cell</td>
    <td>Second cell</td>
    <td>Third cell</td>
    <td><input type="button" onclick="deleteRow('myRow2')" value="Delete"/></td>
  </tr>
  <tr id="myRow3">
    <td>First cell</td>
    <td>Second cell</td>
    <td>Third cell</td>
    <td><input type="button" onclick="deleteRow('myRow3')" value="Delete"/></td>
  </tr>
</table><br>

<script>
function deleteRow(myRow) {
    var row = document.getElementById(myRow);
    var total_cell=document.getElementById('table1').rows[0].cells.length;

   for(i=0;i<total_cell;i++)
   {
    row.deleteCell(0);
    }
  
}

</script>

</body>
</html>


Using JQuery:


<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
table, td {
    border: 1px solid black;
}
</style>
</head>
<body>
<table id="table1">
  <tr id="myRow1">
    <td>First cell</td>
    <td>Second cell</td>
    <td>Third cell</td>
    <td><input type="button" onclick="deleteRow(this)" value="Delete"/></td>
  </tr>
  <tr id="myRow2">
    <td>First cell</td>
    <td>Second cell</td>
    <td>Third cell</td>
    <td><input type="button" onclick="deleteRow(this)" value="Delete"/></td>
  </tr>
  <tr id="myRow3">
    <td>First cell</td>
    <td>Second cell</td>
    <td>Third cell</td>
    <td><input type="button" onclick="deleteRow(this)" value="Delete"/></td>
  </tr>
</table><br>



<script>
function deleteRow(this_row) {
    $(this_row).closest("tr").html("");
  
}
</script>

</body>
</html>