Search code examples
javascriptdomjavascript-objects

How can I add old input value to new input value?


let currencySymbol = '$';
document.querySelector('.pay').addEventListener('click', (e) => {
  e.preventDefault();

  // Get input cash received field value, set to number
  let amount = document.querySelector('.received').value;
  amount *= 1;

  // Set cashReturn to return value of pay()
  let cashReturn = pay(amount);

  let paymentSummary = document.querySelector('.pay-summary');
  let div = document.createElement('div');

  // If total cash received is greater than cart total thank customer
  // Else request additional funds
  if (cashReturn >= 0) {
    div.innerHTML = `
            <p>Cash Received: ${currencySymbol}${amount}</p>
            <p>Cash Returned: ${currencySymbol}${cashReturn}</p>
            <p>Thank you!</p>
        `;
  } else {
    // reset cash field for next entry
    document.querySelector('.received').value = '';
    div.innerHTML = `
            <p>Cash Received: ${currencySymbol}${amount}</p>
            <p>Remaining Balance: ${cashReturn}$</p>
            <p>Please pay additional amount.</p>
            <hr/>
        `;
  }

  paymentSummary.append(div);
});



let totalPaid = 0;

function pay(totalPaid) {
  let cartSum = 50; //using a dummy value for snippet
  return totalPaid - cartSum;
}
.checkout-container {
  max-width: 34em;
  padding: 2em;
  background: #efefef;
}
<div class="checkout-container">
  <h2>Checkout</h2>
  <div class="checkout">
    <div class="cart-total"></div>
    <form>
      <label>Enter Cash Received:</label>
      <input class="received" type="text">
      <button class="pay">Submit</button>
    </form>
    <h3>Receipt</h3>
    <div class="pay-summary"></div>
  </div>
</div>

I'm implementing a simple cash register where user enters how much they paid into an input field, and it will subtract it from the total cost of the items. If the number returned is positive, it shows that the customer wil be given back the remaining change. If it's a negative value, the customer needs to add more money into the input field, which should be summed with their previous input.

Right now, the previous value is not being added to the new value: enter image description here

After I input the remaining $15, there should be 0 remaining balance.


Solution

  • Your amount variable only represents the last input. Any previous submitted amounts are lost. To fix this, define amount as a global variable, and add to that what the user has entered.

    So change this part:

    document.querySelector('.pay').addEventListener('click', (e) => {
      e.preventDefault();
    
      // Get input cash received field value, set to number
      let amount = document.querySelector('.received').value;
      amount *= 1;
    

    to:

    let amount = 0; // <--- define here so to accumulate paid amounts
    document.querySelector('.pay').addEventListener('click', (e) => {
      e.preventDefault();
    
      // Get input cash received field value, set to number
      let paid = document.querySelector('.received').value;
      amount += +paid; // <--- accumulate
    

    Your adapted snippet:

    let currencySymbol = '$';
    let amount = 0; // <--- define here so to accumulate paid amounts
    document.querySelector('.pay').addEventListener('click', (e) => {
      e.preventDefault();
    
      // Get input cash received field value, set to number
      let paid = document.querySelector('.received').value;
      amount += +paid; // <--- accumulate
    
      // Set cashReturn to return value of pay()
      let cashReturn = pay(amount);
    
      let paymentSummary = document.querySelector('.pay-summary');
      let div = document.createElement('div');
    
      // If total cash received is greater than cart total thank customer
      // Else request additional funds
      if (cashReturn >= 0) {
        div.innerHTML = `
                <p>Cash Received: ${currencySymbol}${amount}</p>
                <p>Cash Returned: ${currencySymbol}${cashReturn}</p>
                <p>Thank you!</p>
            `;
      } else {
        // reset cash field for next entry
        document.querySelector('.received').value = '';
        div.innerHTML = `
                <p>Cash Received: ${currencySymbol}${amount}</p>
                <p>Remaining Balance: ${cashReturn}$</p>
                <p>Please pay additional amount.</p>
                <hr/>
            `;
      }
    
      paymentSummary.append(div);
    });
    
    
    
    let totalPaid = 0;
    
    function pay(totalPaid) {
      let cartSum = 50; //using a dummy value for snippet
      return totalPaid - cartSum;
    }
    .checkout-container {
      max-width: 34em;
      padding: 2em;
      background: #efefef;
    }
    <div class="checkout-container">
      <h2>Checkout</h2>
      <div class="checkout">
        <div class="cart-total"></div>
        <form>
          <label>Enter Cash Received:</label>
          <input class="received" type="text">
          <button class="pay">Submit</button>
        </form>
        <h3>Receipt</h3>
        <div class="pay-summary"></div>
      </div>
    </div>