Detect when rows are inserted and deleted in a Jquery table?

1

I need that when you insert a row in the table to be able to capture that event to be able to calculate the total of ages and in the case that rows are eliminated subtract the ages thanks.

I tried using onchange and update without results:

$("#table_datos").on("change", function() {
        alert("cambio detectado");
    });

    $('#table_datos').on('update', function(){
        alert("cambio detectado");
    });


    <table id="table_datos">
          <thead>
            <tr id="1">
              <th>Nombre</th>
              <th>Edad</th>
            </tr>
          </thead>

          <tbody>
            <tr id="2">
              <td>Jorge</td>
              <td>18</td>
            </tr>
            <tr>
              <td>Juan</td>
              <td>21</td>
            </tr>
          </tbody>
        </table>

    $('#table_datos').append('<tr id='+token+'><td>'+variable1+'</td><td >'+variable2+'</td><td><button  type="button" onclick="Eliminar('+token+');"> Eliminar </button></td></tr>')


    function Eliminar(token){

     $('#'+token).remove();

    }
    
asked by Javier Antonio Aguayo Aguilar 12.07.2017 в 23:30
source

1 answer

0

Create an event that detects the change you can do it in two ways:

$('#table_datos tbody').on('change', function() {
  console.log("hola")
})

or in this other way:

$('#table_datos tbody').change(function() {
  console.log("hola")
})

but there seems to be a problem, no change is detected with just that event created.

to call the event we would have to make the event run, there are also two ways:

$('#table_datos').change();

or

$('#table_datos').trigger('change');

var token = 3;
var variable1 = "JuankGlezz";
var variable2 = 25;

$(function() {
  $('#table_datos').append('<tr id=' + token + '><td>' + variable1 + '</td><td >' + variable2 + '</td><td><button  type="button" onclick="Eliminar(' + token + ');"> Eliminar </button></td></tr>')

  $('#table_datos').on('change', function() {
    console.log("hola")
  })
  //llamando al cambio por .trigger() debido al .append()
  $('#table_datos').trigger('change')
});


function Eliminar(token) {
  $('#' + token).remove();
  //llamando al evento de cambio con .change() debido a la eliminacion del dato
  $('#table_datos').change()
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="table_datos">
  <thead>
    <tr id="1">
      <th>Nombre</th>
      <th>Edad</th>
    </tr>
  </thead>

  <tbody>
    <tr id="2">
      <td>Jorge</td>
      <td>18</td>
    </tr>
    <tr>
      <td>Juan</td>
      <td>21</td>
    </tr>
  </tbody>
</table>
    
answered by 13.07.2017 / 00:01
source