Ok i have this table where the last column is a number only column and is formatted with thousand separators and decimal.
Here’s a sample code:
<html>
<head>
<script src="jquery.js"></script>
<script src="includes/autoNumeric.js"></script>
<script type="text/javascript">
$(document).ready(function() {
jQuery(function($) {
$('input.auto').autoNumeric();
});
$("#table").keyup(function(){
var sal_total = 0;
$(".salary[value!='']").each(function() {
sal_total += Number($(this).val());
});
$('#total').val(sal_total);
});
$("#addRow").click(function() {
var newRow = "<tr><td><input type=\"text\"></td><td><input type=\"text\"></td><td><input type=\"text\" class=\"auto salary\"></td></tr>";
$("#table tr.totalRow:last").before(newRow);
});
});
</script>
</head>
<body>
<table id="table" border="1">
<tr>
<td>ID</td>
<td>Name</td>
<td>Salary</td>
</tr>
<tr>
<td><input type="text" ></td>
<td><input type="text" ></td>
<td><input type="text" class="auto salary"></td>
</tr>
<tr>
<td><input type="text" ></td>
<td><input type="text" ></td>
<td><input type="text" class="auto salary"></td>
</tr>
<tr>
<td><input type="text" ></td>
<td><input type="text" ></td>
<td><input type="text" class="auto salary"></td>
</tr>
<tr>
<td colspan="2">Total</td>
<td><input type="text" id="total" readonly="readonly" /></td>
</tr>
</table>
<div align="center">
<input type="button" id="addRow" value="Add Row" />
<input type="submit" name="save" value="Save" />
</div>
</body>
</html>
The salary column is automatically formatted with autoNumeric plugin to insert comma every thousand and put decimal point, i would like to add those salary values every keypress and put the sum in input#total. It works when i remove the commas but produces NaN when there is, plus whenever i add a row autoNumeric does not work on that particular row. Please help I’m just a newbie on this.
To convert to actual numbers (rather than strings), you have to remove the commas.
Change this:
to this:
This will remove commas and dollar signs before attempting to convert it to a number.
If you want the commas back in when you place the total back into the page, you will have to reinsert the commas after you’ve obtained the total.