Dynamically delete rows from HTML Table with AJAX

0

I have a code which should enter or delete the last row as we need an HTML table with AJAX

These are my buttons:

<button class="btn btn-success addmore" type="button" id="insert-more"> Agregar Artículo</button>              
<button class="btn btn-success removebutton" type="button" id="delete-more"> Eliminar Último artículo</button>

And this is the AJAX code:

 $("#insert-more").click(function () {
 $("#mytable").each(function () {
     var tds = '<tr>';
     jQuery.each($('tr:last td', this), function () {
         tds += '<td>' + $(this).html() + '</td>';
     });
     tds += '</tr>';
     if ($('tbody', this).length > 0) {
         $('tbody', this).append(tds);
     } else {
         $(this).append(tds);
     }
 });
});


$("#delete-more").click(function () {
 $("#mytable").each(function () {
          var tds = '<tr>';
     jQuery.each($('tr:last td', this), function () {
         tds += '<td>' + $(this).html() + '</td>';
     });
     tds += '</tr>';
     if ($('tbody', this).length > 0) {
         $('tbody', this).remove(tds);
     } else {
         $(this).remove(tds);
     }
 });
 });

The button to add rows works perfectly, the one that does not work is to eliminate them, I thought I understood the .remove of Ajax but I see no.

    
asked by Alberto Cepero de Andrés 31.07.2017 в 21:06
source

1 answer

2

Hello try replacing the function with:

$("#delete-more").click(function () {
    $('#mytable tr:last-child').remove();
}

I leave you a complete example but also change the add column ..

var i = 1;
 
function agregarFila() {
  $("#dataTable").append("<tr><td>" + i + "</td><td>"+ i*10 +"</td></tr>");
  i += 1;
}

function quitarFila() {
   $('#dataTable tr:last-child').remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button" onclick="agregarFila()">agregar</button>
<button type="button" onclick="quitarFila()">quitar</button>
<table id="dataTable">
</table>
    
answered by 31.07.2017 / 21:22
source