To keep a "running" total of values, the sum
variable must be kept outside the event handler - otherwise, each keyup resets the sum.
The minimal change to your code is to move the variable definition and clear the input.
As there's (intended to be) only one input, you don't need the .each
as this
will be current input receiving the event. To be complete, this
is the input because you're using function() {
if you used ()=>
it would not be the input - see other SO questions for clarity on arrow functions and this
.
var sum = 0;
$('.qtty').keyup(function() {
sum += Number($(this).val());
$(this).val("");
$('#totalQtty').val(sum);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Quantity</h3>
<h4>
Qtty<br>
<input type='text' class='qtty' />
</h4>
<input type='text' id='totalQtty' disabled />
Note: as-is, this will only allow single digit "inputs", eg 5,3,5. To input a number >9 you'll need a "trigger" to tell your system to add that value.
Option option is to require the user to press enter between each value.
Your video-sample also showed previously entered values, you can add these various different ways, below I've put them in <span>
in an box.
Finally, a clear button just means you don't need to reload to reset - note the .val("")
for inputs and .html("")
for the values output.
var sum = 0;
$('.qtty').keyup(function(evt) {
if (evt.which == 13) {
num = Number($(this).val());
sum += num;
$("#values").append(`<span>${num}</span>`);
$(this).val("");
$('#totalQtty').val(sum);
}
});
$("#clear").click(() => {
sum = 0;
$(".qtty,#totalQtty").val("");
$("#values").html("");
});
#values span { display:block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Quantity</h3>
<h4>
Qtty<br>
<input type='text' class='qtty' />
</h4>
<input type='text' id='totalQtty' disabled />
<button id='clear'>clear</button>
<hr/>
<div id='values'></div>