Home > Software engineering >  How can I add old input value to new input value?
How can I add old input value to new input value?

Time:12-29

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 >
  <h2>Checkout</h2>
  <div >
    <div ></div>
    <form>
      <label>Enter Cash Received:</label>
      <input  type="text">
      <button >Submit</button>
    </form>
    <h3>Receipt</h3>
    <div ></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.

CodePudding user response:

If you mean to type an amount of cash received more than once, you need to keep track of the amount of money received so far.

There are multiple ways to achieve that, here I opted for keeping track of it inside the value of an added input element.

In my demo the function cartTotal() always returns 78.45 as the amount to pay, and to reset the amount of money received so far, you just need to click the reset button so that the corresponding input value will be set back to zero.

function pay(totalPaid){
  let cartSum = cartTotal();
  return totalPaid - cartSum;
}

//Arbitrary number
function cartTotal(){
  return 78.45;
}

function resetGame(){
  document.getElementById('sofar').value = 0;
  document.getElementById('received').value = 0;
  document.getElementById('cashreturn').value = 0;
}

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

    // Get input cash received field value, set to number
    const amount =  parseFloat( document.getElementById('received').value );
    
    //**Here updates the amount received so far
    const receivedSoFar =  parseFloat( document.getElementById('sofar').value );
    document.getElementById('sofar').value = receivedSoFar   amount;

    // Set cashReturn to return value of pay()
    const cashReturn = pay(amount   receivedSoFar);
    document.getElementById('cashreturn').value = cashReturn.toFixed(2);
    
  });
body{
  font-family: sans-serif;
}

input, button{
  padding: .2rem;
  width: 5rem;
  font-size: 15px;
}

input[disabled]{
  outline: none;
  border: none;
  font-size: 20px;
}

button{
  cursor: pointer;
}
<label>Enter cash:</label>
<input type="text" id="received">
<button >PAY</button>
<hr>
<label>Received so far:</label>
<input type="text" id="sofar" readonly disabled value="0">
<br>
<label>Cash return:</label>
<input type="text" id="cashreturn" readonly disabled value="0">
<br>
<button onclick="resetGame();">RESET</button>

CodePudding user response:

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 >
  <h2>Checkout</h2>
  <div >
    <div ></div>
    <form>
      <label>Enter Cash Received:</label>
      <input  type="text">
      <button >Submit</button>
    </form>
    <h3>Receipt</h3>
    <div ></div>
  </div>
</div>

  • Related