I am trying to add the weight column and show it in my <span id="ptotal">
the problem is that it always returns zero.
$(document).on('keyup','#datatable-buttons input.peso',function(){
peso = $(this).val();
sumar();
});
function sumar(){
pesostotal = 0;
$("#datatable-buttons tr").each(function(){
pesostotal = pesostotal + $(this).find('td:eq(2)').text();
alert(pesostotal); // lo puse por debugger Muestra 0 siempre!
});
$('#ptotal').text(pesostotal);
}
html
<table id="datatable-buttons" class="table table-striped table-bordered dataTable no-footer dtr-inline" role="grid" aria-describedby="datatable-buttons_info" style="width: 100%;">
<thead>
<tr role="row">
<th class="sorting_asc" tabindex="0" aria-controls="datatable-buttons" rowspan="1" colspan="1" style="width: 50px;" aria-sort="ascending" aria-label="Name: activate to sort column descending">#</th>
<th class="sorting" tabindex="0" aria-controls="datatable-buttons" rowspan="1" colspan="1" style="width: 200px;" aria-label="Position: activate to sort column ascending">Calidad</th>
<th class="sorting" tabindex="0" aria-controls="datatable-buttons" rowspan="1" colspan="1" style="width: 50px;" aria-label="Office: activate to sort column ascending">Peso</th>
<th class="sorting" tabindex="0" aria-controls="datatable-buttons" rowspan="1" colspan="1" style="width: 50px;" aria-label="Age: activate to sort column ascending">Cajas</th>
<th class="sorting" tabindex="0" aria-controls="datatable-buttons" rowspan="1" colspan="1" style="width: 50px;" aria-label="Start date: activate to sort column ascending">Precio</th>
</thead>
<tbody>
<?php if(!empty($calidad)): ?>
<?php foreach($calidad as $calidad): ?>
<tr role="row" class="odd">
<td tabindex="0" class="sorting_1"><input type="hidden"><?php echo $calidad->id; ?></td>
<td><?php echo $calidad->nombre; ?></td>
<td><input type="number" name="peso" placeholder="0" class="form-control peso"></td>
<td><input type="number" name="cajas" placeholder="0" class="form-control cajas"></td>
<td><input type="number" name="precio" placeholder="0" class="form-control precio"></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
I have changed your code considering firstly the case of how you get the value you do it with
text()
and what you should do withval()
it because it is an input. On the other hand, you can use the same selector to add your inputs#datatable-buttons input.peso
, whichever changes, and finally you should validate if the value you add is or is not a validated value, since if you don't, your variable will become a NaN.pesostotal
The problem is that the value inside your
td
is not in thehtml
owntd
but in ainput
. You have to access thechildren
deltd
and then the value ofinput
(or search for theclosest
input
, whichever works best for you). You also have to transform the value to a number so that it does not take it as text and concatenate it (in this case I usedNumber()
).Here is a summarized example: