Js: Sum Column Values And Updating Result On Change
I have a table where, for each row, I must show the sum of two columns and present it in a third one. The sum must be calculated everytime any of the inputs change. Each row has a
Solution 1:
You can use this code.
Add for each input (which the value gonna be taken from) this class for example:
toBeCalced
, and for each input which the total will be showed in, this class for example total
.
In JS we gonna use JQuery to listen to change
event, and do these steps:
- go to parent row.
- iterate over each children with class
toBeCalced
and add its value tototal
variable. - Get the total input by class name
total
and set the total value.
We get this result:
$(document).ready(function() {
$('.toBeCalced').change(function() {
var row = $(this).closest('tr');
var valuesToSum = row.find('.toBeCalced');
var total = 0;
$.each(valuesToSum, function(index, item) {
total += parseInt($(item).val());
});
var totalInput = row.find('.total')[0];
$(totalInput).val(total);
});
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><tbody><tr><td>Element Name ABC</td><td><divclass="form-group"><div><inputid="SM-J3D-01-1"type="number"min="0"step="1"name="Validos"class="toBeCalced form-control"value="0" /><spanclass="text-danger field-validation-valid"data-valmsg-for="Validos"data-valmsg-replace="true"></span></div></div></td><td><divclass="form-group"><div><inputid="SM-J3D-01-1"type="number"min="0"step="1"name="Cortesia"class="toBeCalced form-control"value="0" /><spanclass="text-danger field-validation-valid"data-valmsg-for="Cortesia"data-valmsg-replace="true"></span></div></div></td><td><divclass="form-group"><div><inputid="SM-J3D-01-1"type="number"readonlyname="Total"class="total form-control"value="0" /><spanclass="text-danger field-validation-valid"data-valmsg-for="Total"data-valmsg-replace="true"></span></div></div></td></tr>
//Begining second row
<tr><td>Element Name XYZ</td><td><divclass="form-group"><div><inputid="SM-J3D-01-2"type="number"min="0"step="1"name="Validos"class="toBeCalced form-control"value="0" /><spanclass="text-danger field-validation-valid"data-valmsg-for="Validos"data-valmsg-replace="true"></span></div></div></td><td><divclass="form-group"><div><inputid="SM-J3D-01-2"type="number"min="0"step="1"name="Cortesia"class="toBeCalced form-control"value="0" /><spanclass="text-danger field-validation-valid"data-valmsg-for="Cortesia"data-valmsg-replace="true"></span></div></div></td><td><divclass="form-group"><div><inputid="SM-J3D-01-2"type="number"readonlyname="Total"class="total form-control"value="0" /><spanclass="text-danger field-validation-valid"data-valmsg-for="Total"data-valmsg-replace="true"></span></div></div></td></tr></tbody></table>
Post a Comment for "Js: Sum Column Values And Updating Result On Change"