2017-08-29 5 views
0

Je souhaite effectuer des opérations mathématiques dans un tableau en modifiant les valeurs d'entrée dans les cellules et en utilisant l'événement jquery onkeyup.DataTables et jQuery pour effectuer des calculs dans une table

<table id="GVHabvar"> 
    <tbody> 
     <tr> 
      <td> 
       <input id="cantidad" name="cantidad" type="text" class = "calculo"> 
      </td> 
      <td> 
       <input id="precio" name="precio" type="text" class = "calculo"> 
      </td> 
      <td> 
       <input id="valor" name="valor" type="text"> 
      </td> 
     </tr> 
     <tr> 
      <td> 
       <input id="cantidad" name="cantidad" type="text" class = "calculo"> 
      </td> 
      <td> 
       <input id="precio" name="precio" type="text" class = "calculo"> 
      </td> 
      <td> 
       <input id="valor" name="valor" type="text"> 
      </td> 
     </tr> 
     <tr> 
      <td> 
       <input id="cantidad" name="cantidad" type="text" class = "calculo"> 
      </td> 
      <td> 
       <input id="precio" name="precio" type="text" class = "calculo"> 
      </td> 
      <td> 
       <input id="valor" name="valor" type="text"> 
      </td> 
     </tr> 
    </tbody> 
</table> 

Ceci est mon essai, mais il ne fonctionne pas bien avec datatables (par exemple avec pagination)

$(document).ready(function() { 
     var filas = $("#GVHabvar tbody tr"); 
     filas.each(function (index) { 
      var fila = $(this); 
      fila.find('.calculo').on('keyup', function() { 
       var cantidad = ($.isNumeric(fila.find("#cantidad").val())) ? fila.find("#cantidad").val() : 0; 
       var precio = ($.isNumeric(fila.find("#precio").val())) ? fila.find("#precio").val() : 0; 
       var valor = parseInt(cantidad, 10) * parseInt(precio, 10); 
       fila.find('#valor').val(valor); 
      }); 
     }); 
    }); 

Répondre

1

Une façon de faire est d'utiliser les datatables rowCallback. Cet événement se déclenche après que chaque ligne est dessinée et peut être utilisé pour lier votre événement de touche. La façon dont vous le faisiez n'affectait que les données de la table visible, comme vous l'avez découvert.

var table = $('#GVHabvar').DataTable({ 
    "rowCallback": function (row, data, index) { 
     var fila = $(row); 
     fila.find('.calculo').on('keyup', function() { 
      var cantidad = ($.isNumeric(fila.find("#cantidad").val())) ? fila.find("#cantidad").val() : 0; 
      var precio = ($.isNumeric(fila.find("#precio").val())) ? fila.find("#precio").val() : 0; 
      var valor = parseInt(cantidad, 10) * parseInt(precio, 10); 
      fila.find('#valor').val(valor); 
     }); 
    } 
}); 

Voici un travail jsfiddle

+0

fonctionne exactement comme je veux! – DavidM