I have a table in which I'm trying to add and subtract multiple text fields using jQuery on keydown
or blur
. While I can add successfully, I get all wrong results for subtraction.
HTML:
<input type="text" class="add" />
<input type="text" class="add" />
<input type="text" class="sub" />
<input type="text" class="sub" />
<label id="total"></label>
JS:
$('.add').blur(function () {
var sum = 0;
$('.add').each(function () {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
$('#total').text(sum.toFixed(2));
});
$('.sub').blur(function () {
var sum = 0;
var val = $('#total').text();
$('.sub').each(function () {
if (!isNaN(this.value) && this.value.length != 0) {
sum -= parseFloat(this.value);
}
});
val = parseFloat(sum) - parseFloat(val);
$('#total').text(val);
});