I want to perform mathematical operations in a table by changing the input values inside the cells and using the jquery onkeyup event.
<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>
This is my try, but it doesn't work well with datatables (e.g. with 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);
});
});
});
One way to do this is to use the datatables rowCallback. This event fires after each row is drawn and can be used to bind your keyup event. The way you were doing it was only affecting the visible table data, as you discovered.
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);
});
}
});
Here is a working jsfiddle