Adsense
Popular Posts
- Install APXS in Redhat Linux
- MySQL workbench -"Could not decrypt password cache"
- Transfer modules between sites
- JavaScript, remove trailing insignificant zeros after toFixed function
- Set Windows path command line
- datatable order by nunmeric
- MySQL date created and date modified
- super(props) in React
- PHP, dump varailbes in a format way
- React: connect(mapStateToProps, mapDispatchToProps)
Thursday, November 20, 2014
jQuery - sum over columns in a table or over input box
I have a table, there is an input box in a column, beside there is default value near input box.
There are also default values inside input box. I want to add a summary row to show total.
When the input value is changed, the total row also needs to reflect the change.
below is the code:
$(document).ready(function() {
var $resultTable = $("<table class='list'></table>");
var $header = $("<tr><th>#</th><th>Saving</th>");
$resultTable.html($header);
for(var i = 0; i< 10; i++){
var $row = $("<tr><td >"+(i+1)+"</td><td> <input type='text' class='inputch' name='saving' size ='6' value='"+i+"'>(<label class='inputch0'>"+i+"</label>)</td> </tr>");
$resultTable.append($row);
}
var $row1 = $("<tr><td>Total</td><td><td class='totalch'> 0</td></tr>");
var total = 0;total0=0;
$resultTable.find('input.inputch').each(function() {
total += Number($(this).val());
});
$resultTable.find('label.inputch0').each(function() {
total0 += Number($(this).html());
});
$resultTable.find('td.totalch').html(total+' ('+total0+')');
$resultTable.find('input.inputch').change(function() {
var total = 0;total0=0;
$resultTable.find('input.inputch').each(function() {
total += Number($(this).val());
});
$resultTable.find('label.inputch0').each(function() {
total0 += Number($(this).html());
});
$resultTable.find('td.totalch').html(total+' ('+total0+')');
});
});
We use change in input box, the total will be changed only after input box lose focus.
If we want to see the immediate change, we can use keyup, i.e.
$resultTable.find('input.inputch').keyup(function() {
OR
$resultTable.find('input.inputch').on('input', function() {
Labels:
jQuery
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment