JQuery Table Input Additions
final version
by Joe Saad
HTML
<table border="1" bordercolor="#FFCC00" width="400">
<tr>
<th>Table Col 1</th>
<th>Table Col 2</th>
<th>Table Col 3</th>
<th>Table Col 4</th>
</tr>
<tr>
<td>00</td>
<td><input type="text" value="42" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
</tr>
<tr>
<td>10</td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
</tr>
<tr>
<td>20</td>
<td><input type="text" /></td>
<td><input type="text" value="53" /></td>
<td><input type="text" /></td>
</tr>
<tr class="totals">
<td>Totals</td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
CSS
input {width:35px;}
JavaScript
$(document).ready(function() {
var total = 0;
var totals = new Array();
/* for (y=0;y<=5;y++){
totals[y]= 0;
}
*/
totals[0] = 0;
totals[1] = 0;
totals[2] = 0;
totals[3] = 0;
totals[4] = 400;
$("input").each(function() {
var col = $(this).parents("tr").children("td").index($(this).parent());
var modCol = col + 1;
var row = $(this).parents("tr").index();
if (this.value == "") {
this.value = 0;
}
totals[col] = parseInt(totals[col]) + parseInt(this.value);
// alert(totals[1]);
//total = parseInt(total) + parseInt(this.value);
$(".totals td:nth-child(" + modCol + ")").text(totals[col]);
});
$("td input").focus(function() {
var col = $(this).parents("tr").children("td").index($(this).parent());
var modCol = col + 1;
totals[col] = parseInt(totals[col]) - parseInt(this.value);
if (this.value == 0) {
this.value = "";
}
});
$("input").blur(function() {
var col = $(this).parents("tr").children("td").index($(this).parent());
var modCol = col + 1;
var row = $(this).parents("tr").index();
//alert(this.value);
if (this.value == "") {
this.value = 0;
}
totals[col] = parseInt(totals[col]) + parseInt(this.value);
// alert(totals[1]);
//total = parseInt(total) + parseInt(this.value);
$(".totals td:nth-child(" + modCol + ")").text(totals[col]);
});
});