How to delete the last row of the table?

2
<table class="table">
  <thead>
    <tr>
        <th>#</th>
        <th>Id.</th>
        <th>Descrição</th>
        <th>Qtd.</th>
        <th>Unitário</th>
        <th>Total</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th> 1 </th>
      <td> 10</td>
      <td> 20</td>
      <td> 10 </td>
      <td> 30 </td>
      <td> 300 </td>
    </tr>
    <tr>
      <th> 2 </th>
      <td> 40</td>
      <td> 50</td>
      <td> 10 </td>
      <td> 60 </td>
      <td> 600 </td>
    </tr>
  </tbody>
</table>
<button 
  type="button" 
  class="btn" 
  id="btnexcluirultima">ExcluirUltimaLinha</button>

<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
<script type="text/javascript">
  $("#btnexcluirultima").on('click', function(){
    //Excluir a ultima linha da tabela
    $(".table td").closest('td').remove();
  });

I need only delete the last row of the table! How do I, by the way, do the way I did, delete all the rows from the table ... what I did wrong, right away, thank you!

    
asked by anonymous 20.06.2018 / 02:07

2 answers

3

Use the :last selector. To delete a line you select tr , not td :

$("#btnexcluirultima").on('click', function(){
    //Excluir a ultima linha da tabela
    $(".table tr:last").remove();
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tableclass="table">
  <thead>
    <tr>
        <th>#</th>
        <th>Id.</th>
        <th>Descrição</th>
        <th>Qtd.</th>
        <th>Unitário</th>
        <th>Total</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th> 1 </th>
      <td> 10</td>
      <td> 20</td>
      <td> 10 </td>
      <td> 30 </td>
      <td> 300 </td>
    </tr>
    <tr>
      <th> 2 </th>
      <td> 40</td>
      <td> 50</td>
      <td> 10 </td>
      <td> 60 </td>
      <td> 600 </td>
    </tr>
  </tbody>
</table>
<button 
  type="button" 
  class="btn" 
  id="btnexcluirultima">ExcluirUltimaLinha</button>
    
20.06.2018 / 02:10
1

$(function () {

    $('#btnexcluirultima').on('click', function () {
        var trs = $('.table').find('tr');

        if (trs.length > 1)
          trs.last().remove();
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tableclass="table">
  <thead>
    <tr>
        <th>#</th>
        <th>Id.</th>
        <th>Descrição</th>
        <th>Qtd.</th>
        <th>Unitário</th>
        <th>Total</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th> 1 </th>
      <td> 10</td>
      <td> 20</td>
      <td> 10 </td>
      <td> 30 </td>
      <td> 300 </td>
    </tr>
    <tr>
      <th> 2 </th>
      <td> 40</td>
      <td> 50</td>
      <td> 10 </td>
      <td> 60 </td>
      <td> 600 </td>
    </tr>
  </tbody>
</table>
<button 
  type="button" 
  class="btn" 
  id="btnexcluirultima">ExcluirUltimaLinha</button>
    
20.06.2018 / 02:15