Build a Cash Register Project - Build a Cash Register

Tell us what’s happening: Okay, so I have been at this for two days. I keep getting it to where it will almost be perfect, but everything will work except the alert and messages and I can’t figure out why. Please help in any way you can.

const cashInput = document.getElementById('cash');
const changeDue = document.getElementById('change-due');
const purchaseBtn = document.getElementById('purchase-btn');
const cidDisplay = document.getElementById('cash-in-drawer'); 

const purchaseCalculation = () => {
  let price;
  let cid;

  price = 19.5;
  cid = [
    ["PENNY", 1.01],
    ["NICKEL", 2.05],
    ["DIME", 3.1],
    ["QUARTER", 4.25],
    ["ONE", 90],
    ["FIVE", 55],
    ["TEN", 20],
    ["TWENTY", 60],
    ["ONE HUNDRED", 100]
  ];

  let cash = parseFloat(cashInput.value);
  let change = cash - price;

  if (cash < price) {
    alert('Customer does not have enough money to purchase the item');
    return;
  } 
  
  if (cash === price) {
    changeDue.textContent = "No change due - customer paid with exact cash";
    return;
  } 

  let changeArr = [];
  let cidTotal = 0;
  for (let [_, amount] of cid) {
    cidTotal += amount;
  }

  if (change > cidTotal) {
    changeDue.textContent = "Status: INSUFFICIENT_FUNDS";
    return;
  } else if (change === cidTotal) {
    changeDue.textContent = "Status: CLOSED";
    return;
  }

  for (let i = cid.length - 1; i >= 0; i--) {
    const [unit, amount] = cid[i];
    const unitValue = parseFloat(unit === "ONE HUNDRED" ? 100 : unit === "TWENTY" ? 20 : unit === "TEN" ? 10 : unit === "FIVE" ? 5 : unit === "ONE" ? 1 : unit === "QUARTER" ? 0.25 : unit === "DIME" ? 0.1 : unit === "NICKEL" ? 0.05 : 0.01);
    let numUnits = Math.min(Math.floor(change / unitValue), amount);
    if (numUnits > 0) {
      changeArr.push([unit, numUnits * unitValue]);
      change = Math.round((change - numUnits * unitValue) * 100) / 100;
    }
  }
  
  let changeMessage = "Status: OPEN ";
  for (let i = 0; i < changeArr.length; i++) {
    changeMessage += `${changeArr[i][0]}: $${changeArr[i][1]} `;
  }
  changeDue.textContent = changeMessage;
};

purchaseBtn.addEventListener("click", purchaseCalculation);

cidDisplay.innerHTML = "<p><strong>Cash in Drawer:</strong></p>";
cid.forEach(item => {
  cidDisplay.innerHTML += `<p>${item[0]}: $${item[1]}</p>`;
});

WARNING

The challenge seed code and/or your solution exceeded the maximum length we can port over from the challenge.

You will need to take an additional step here so the code you wrote presents in an easy to read format.

Please copy/paste all the editor code showing in the challenge from where you just linked.

Replace these two sentences with your copied code.
Please leave the ``` line above and the ``` line below,
because they allow your code to properly format in the post.

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0

Challenge Information:

Build a Cash Register Project - Build a Cash Register

one see I thing immediately is that cid and price need to be global values

1 Like

please provide your html too


I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

I had completely missed that! Thank you so much!

Here is the HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Cash Register" />
    <title>Cash Register</title>
    <link href="styles.css" rel="stylesheet"/>
  </head>
	<body>
    <h1>Cash Register</h1>
      <div id="container">
        <div id="register-top">
          <label for="cash">Enter Amount Given: </label>
          <input id="cash">
          <p id="price">Price: $19.50</p>
          <p id="total-screen"></p>
        </div>
        <div id="connector"></div>
        <div id="register-bottom">
          <button id="purchase-btn">Purchase</button>
          <div id="change-due"></div>
          <div id="cash-in-drawer"></div>
        </div>
        <div id="divider"></div>
        <div id="stand"></div>
      </div>
      
      <script src="script.js">

  </script>
  </body>
</html>

there seems to be something not completely right in your calculation of the change, you are giving more change than what you have (like cid Twenty is $60 but the change due is TWENTY $80)

Thank you so much for your help. I decided to scrap the calculation and start over fresh in the morning. Sometimes the brain is just done for the day, no matter how frustrating lol

Tell us what’s happening:

Hello, it’s me again lol Figured out the calculations, and it all works fine, but the last requirement isn’t being fulfilled and I am entirely uncertain why. Please help so I can finally finish this one and move on to my last lessons.

When price is 19.5 , the value in the #cash element is 20 , cid is [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]] , and the #purchase-btn element is clicked, the value in the #change-due element should be Status: CLOSED PENNY: $0.5 .

Your code so far

const cash = document.getElementById('cash');
const changeDue = document.getElementById('change-due');
const purchase = document.getElementById('purchase-btn');
const cidDisplay = document.getElementById('cash-in-drawer'); 

let price = 19.5;
let cid = [
  ["PENNY", 1.01],
  ["NICKEL", 2.05],
  ["DIME", 3.1],
  ["QUARTER", 4.25],
  ["ONE", 90],
  ["FIVE", 55],
  ["TEN", 20],
  ["TWENTY", 60],
  ["ONE HUNDRED", 100]
];

const statusDisplay = (status, change) => {
  changeDue.innerHTML = `<p>Status: ${status}</p>`;
  change.map(
    money => (changeDue.innerHTML += `<p>${money[0]}: $${money[1]}</p>`)
  );
  return;
};

const purchaseCalculation = () => {
  const cashValue = parseFloat(cash.value);
  let money = {
    "PENNY": 0.01,
    "NICKEL": 0.05,
    "DIME": 0.1,
    "QUARTER": 0.25,
    "ONE": 1,
    "FIVE": 5,
    "TEN": 10,
    "TWENTY": 20,
    "ONE HUNDRED": 100
  }
  let change = cashValue - price;
  const flippedCid = [...cid].reverse();
  const bills = [100, 20, 10, 5, 1, 0.25, 0.1, 0.05, 0.01];
  const given = parseFloat(
    cid
      .map(total => total[1])
      .reduce((prev, curr) => prev + curr)
      .toFixed(2)
  );

  const statusUpdate = { status: 'OPEN', change: [] }

  if (cashValue < price) {
    alert('Customer does not have enough money to purchase the item');
    cash.value = '';
    return;
  }

  if (cashValue === price) {
    changeDue.innerHTML =
      '<p>No change due - customer paid with exact cash</p>';
    cash.value = '';
    return;
  }

  if (given < change) {
    return (changeDue.innerHTML = '<p>Status: INSUFFICIENT_FUNDS</p>');
  } else if (given === change) {
    statusDisplay('CLOSED', change);
    updateNew(change);
  } else {
    let changeArr = [];
    
    for(let i = 0; i < flippedCid.length; i++) {
      if (change > bills[i] && change > 0) {
        let amount = 0;
        let total = flippedCid[i][1];
        while (total > 0 && change >= bills[i]) {
          total -= bills[i];
          change = parseFloat((change - bills[i]).toFixed(2));
          amount++;
        }
        if (amount > 0) {
          statusUpdate.change.push([flippedCid[i][0], amount * bills[i]]);
        }
      }
    }
    if (change > 0) {
      return (changeDue.innerHTML = '<p>Status: INSUFFICIENT_FUNDS</p>');
    }
  }

  statusDisplay(statusUpdate.status, statusUpdate.change);
  updateNew(statusUpdate.change);
};

const isEnough = () => {
  if (!cash.value) {
    return;
  }
  purchaseCalculation();
};

const updateNew = (change) => {
  const moneyName = {
    PENNY: 'Pennies',
    NICKEL: 'Nickels',
    DIME: 'Dimes',
    QUARTER: 'Quarters',
    ONE: 'Ones',
    FIVE: 'Fives',
    TEN: 'Tens',
    TWENTY: 'Twenties',
    'ONE HUNDRED': 'Hundreds'
  };
  
  if (change) {
    change.forEach(changeArr => {
      const myArr = cid.find(cidArr => cidArr[0] === changeArr[0]);
      myArr[1] = parseFloat((myArr[1] - changeArr[1]).toFixed(2));
    });
  }

  cash.value = '';
  cidDisplay.innerHTML = "<p><strong>Cash in Drawer:</strong></p>";
  cid.forEach(item => {
    cidDisplay.innerHTML += `<p>${item[0]}: $${item[1]}</p>`;
  });
};

purchase.addEventListener("click", purchaseCalculation);

cash.addEventListener('keydown', e => {
  if (e.key === 'Enter') {
    purchaseCalculation();
  }
});

updateNew([]);

WARNING

The challenge seed code and/or your solution exceeded the maximum length we can port over from the challenge.

You will need to take an additional step here so the code you wrote presents in an easy to read format.

Please copy/paste all the editor code showing in the challenge from where you just linked.

Replace these two sentences with your copied code.
Please leave the ``` line above and the ``` line below,
because they allow your code to properly format in the post.

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0

Challenge Information:

Build a Cash Register Project - Build a Cash Register

I have merged your two topics, please do not open multiple topics to ask for help for the same challenge or project

the issue is that your #change-due element doesn’t have written the change due when the status is CLOSED

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.