1

I need this code to complete a form I am working on. The code needs to display the result of various inputs after entering them. Here is what I have so far.

<html>
<body>  
    <h3> Quantity </h3>
    <h4>
        Qtty  <br>
        <input type = 'text' class = 'qtty' />
    </h4>
    <input type = 'text' id = 'totalQtty' disabled />
    <script>
        $('.qtty').keyup(function () {
            var sum = 0;
            $('.qtty').each(function() {
                sum += Number($(this).val());
            });
            $('#totalQtty').val(sum);
        });
    </script>
</body>

Any advice on how to proceed? I still am learning and recycling code... Thank you in advance.

David
  • 208,112
  • 36
  • 198
  • 279
  • 1
    Just need more `` to be able to sum: https://jsfiddle.net/na8dqomp/ – freedomn-m Sep 26 '22 at 15:23
  • 2
    If you look at your browser's development console, I suspect you'll see an error pointing you to: [JQuery - $ is not defined](https://stackoverflow.com/q/2194992/328193) – David Sep 26 '22 at 15:23
  • 1
    @freedomn-m I do not want to sum two different inputs, what I meant was to keep typing in the same input and accumulate these values. ie. "5 for chips, 3 for coke, 5 for bananas..." total is 13. – Gilberto Chazaro Sep 26 '22 at 15:28
  • @David I just declared it in my header, I just omitted it here because of space, thank you. – Gilberto Chazaro Sep 26 '22 at 15:30
  • 1
    Thanks for clarifying. The issue there is *when* do you stop adding - if it's single digit, then fine, otherwise if you want to add "15 coke" - you get 1+15 = 16. So you need something other/in addition to keyup - eg check if key is ENTER *then* add the values, or add of click of a button, or just after a timeout/delay/*debounce* (eg after 1s user stops typing, add number and clear). You need to define that. – freedomn-m Sep 26 '22 at 15:30
  • @GilbertoChazaro: Can you provide a runnable [mcve] as a stack snippet which demonstrates the problem then? It's not really clear to me what logic you're trying to implement, so it's not really clear in what way the code shown isn't working as expected? If you only want one input, why do you have `$('.qtty').each(function() {`? What values are you expecting to "sum"? Each instance of the `keyup` function creates a new "sum" value, adds all of your input values to it, and outputs it. – David Sep 26 '22 at 15:32
  • 2
    The change to your code to keep a "running sum" would be to move `var sum=0` *outside* the keyup function - inside it gets reset to 0 each keyup, outside it will keep its value. You'll then need a reset function (or page refresh) to clear it. This keeps a running sum, but only 1 digit at a time (eg type 5 3 5) if you want 2 digits you'll need that "trigger" to start the sum: https://jsfiddle.net/6sfndq41/ – freedomn-m Sep 26 '22 at 15:34
  • @David I am coming from VB and switching to Web, so this is what I wanted to replicate https://chazaro.com/pos.mp4. – Gilberto Chazaro Sep 26 '22 at 15:43
  • Alternatively, you may want the input to include all previous values, eg if the value is "5 3 5" then sum that – freedomn-m Sep 26 '22 at 15:43
  • On the shaky-cam video, how does it know when you've finished typing? There seems to be a short pause after the number is typed to when it appears in the "sum box". Is the user pressing enter? Just waiting? What if you (quickly) type "13" in the box? Do you get 1+3 or 13? – freedomn-m Sep 26 '22 at 15:45
  • @freedomn-m Thank you so much for, Great solution I did not see that, I am just realizing that it is very different web programming from the old windows desktop... – Gilberto Chazaro Sep 26 '22 at 15:46
  • Surprisingly, not really :) You need to get your head around server-side/client-side but after that, most UI elements have very similar equivalents; just knowing/finding the correct syntax. – freedomn-m Sep 26 '22 at 15:49
  • @freedomn-m Oh, it is old vb code you just code in the input and after enter you sum and then add to the other control. I can send you the code if you want. Anyway, thank you again for the solution, it works grat – Gilberto Chazaro Sep 26 '22 at 15:50
  • *and after enter* - so you are pressing enter. See this answer to detect enter key (use your keyup) - ignore the `keypress` answers as they're out of date and you [shouldn't use keypress](https://developer.mozilla.org/en-US/docs/Web/API/Element/keypress_event) anymore: https://stackoverflow.com/a/19312407/2181514 – freedomn-m Sep 26 '22 at 16:07
  • Would this approach work for you: "5 for chips, 3 for coke, 5 for bananas... 10 smth".split(" ").forEach(e => { if ( isNumber(e){sum += e} ) }); The isNumber is a custom function you need to implement, there are great answers on this site. Downside is that "10something" would fail – pszaba Sep 26 '22 at 20:52

1 Answers1

1

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>
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
  • A much better answer, this is exactly what I needed to achieve. Thank you. I´ve learned something new today. – Gilberto Chazaro Sep 26 '22 at 17:18
  • I just copied and pasted it... but is not running... I am so sorry but I do not get it. here is the file https://chazaro.com/x.html – Gilberto Chazaro Sep 26 '22 at 18:29
  • You somehow copied `#values span { display:block; }` inside the ` – Dimitris Maragkos Sep 26 '22 at 21:53
  • @DimitrisMaragkos, My mistake, I fixed it as you said and uploaded the new file... still is not working... – Gilberto Chazaro Sep 27 '22 at 03:51
  • 1
    Classic/Common problem. The snippet and jsfiddle automatically add the script box to the *end* of the body (just before `

    `). If you put the script in the `

    ` then the elements don't exist yet so `$(".qtty").length === 0` and no events get wired. Two options - put your `

    – freedomn-m Sep 27 '22 at 07:46
  • @freedomn-m Thank you man, I feel so dumb for not knowing this. Now it is working fine. :) – Gilberto Chazaro Sep 27 '22 at 13:31