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);
});
I would suggest the next solution:
HTML:
<input type="text" class="calc" data-action="add" />
<input type="text" class="calc" data-action="add" />
<input type="text" class="calc" data-action="sub" />
<input type="text" class="calc" data-action="sub" />
<label id="total"></label>
JS:
$(document.body).on('blur', '.calc', function() {
var result = 0;
$('.calc').each(function() {
var $input = $(this),
value = parseFloat($input.val());
if (isNaN(value)) {
return;
}
var action = $input.data('action') == 'add' ? 1 : -1;
result += value * action;
});
$('#total').text(result.toFixed(2));
});