how to keep adding to JS variable?

前端 未结 1 570
闹比i
闹比i 2021-01-24 18:00

I am trying to continuously add to a js variable every time a user enters a value into a box.

So far if they enter \'21\' the alert will say \'your balance is £12\' but

相关标签:
1条回答
  • 2021-01-24 18:24

    The function which makes the change is attached to a submit button.

    When the user clicks the button:

    1. The JS runs
    2. The value is updated
    3. The value is alerted
    4. The form is submitted
    5. A new page loads
    6. The new page has var firstAmount = 0; in it

    You should:

    • Set the default value dynamically with server side code. See Unobtrusive JavaScript and
    • Prevent the default behaviour of the submit button

    Using an onclick attribute, you need to return false from the event handler function:

    onclick="depositedFunds(); return false;"
    

    Modern code would separate concerns and not tie things so tightly to a specific means of triggering the form submission.

    var firstAmount = 0;
    
    function depositedFunds(e) {
      e.preventDefault();
      var ad = document.getElementById("amountDropped");
      firstAmount = +firstAmount + +ad.value;
      alert("Your balance is £" + firstAmount);
    };
    
    document.querySelector('form').addEventListener('submit', depositedFunds);
    <form method="get">
      <input type="number" id="amountDropped">
      <input type="submit" value="Deposit amount">
    </form>

    0 讨论(0)
提交回复
热议问题