简体   繁体   中英

Simple shopping cart in JavaScript

I'm trying to learning the basics of JavaScript and i was practicing it by making a simple "shopping cart". Its one of my first works I did on JavaScript.

This is what needs to happen:

You need to select an option from the dropdown menu and give in a number (how much you want) in the "input field". That you submit with the button and it needs to show up in the table below with the following information: Name of the product, how much you want, and a subprice. I all got that working.

But these are my problems:

  • First problem: When I select the same product and add it, it adds a new row in the table, and thats not what I want. I needs to count up with the same product you already orderd.
  • Second problem: I don't know how to sum all the subtotals up to get a total price of all products. It needs to change on the go in the html document when you submit a product.

This is my code:

 "use strict"; //Lijst met info van groeten. const allGroenten = [ { naam: "Bloemkool", prijs: 1.15, eenheid: "stuk" }, { naam: "Chinese kool", prijs: 1.95, eenheid: "stuk" }, { naam: "Wortelen", prijs: 0.99, eenheid: "kg" } ]; //DROPDOWN MENU INVULLEN MET DE OBJECTEN VAN ALLGROENTEN const select = document.getElementById("groenten"); for (let i = 0; i < allGroenten.length; i++) { const opt = allGroenten[i].naam; const el = document.createElement("option"); el.text = opt + " - " + "\€" + allGroenten[i].prijs + " /" + allGroenten[i].eenheid; el.value = allGroenten[i].prijs; el.dataset.naam = allGroenten[i].naam; el.id = [i] select.add(el); } // EVENT .onClick op Toevoeg button document.getElementById("toevoegen").onclick = function() { invoerAub.innerText = ""; let aantalCheck = document.getElementById("aantal"); let check = aantalCheck.value; selecteerAub.innerText = ""; let selecteerCheck = document.getElementById("groenten"); let checkSelect = selecteerCheck.value; if (check == false) { const invoerAub = document.getElementById("invoerAub"); invoerAub.innerText = "Aantal ingeven aub."; } else if (checkSelect == false) { const invoerAub = document.getElementById("selecteerAub"); invoerAub.innerText = "Selecteer u groeten aub."; } else { const tbody = document.querySelector("tbody"); const tr = tbody.insertRow(); const naamTd = tr.insertCell(); const naamInput = document.getElementById("groenten"); naamTd.innerText = naamInput.options[naamInput.selectedIndex].text; const aantalTd = tr.insertCell(); const aantalInput = document.getElementById("aantal"); aantalTd.innerText = aantalInput.value; const subtotaalTd = tr.insertCell(); subtotaalTd.dataset.subPrijs = aantalInput.value * naamInput.value; let subtotaalInput = aantalInput.value * naamInput.value; subtotaalTd.innerText = subtotaalInput.toFixed(2); // naamInput.value = ""; // aantalInput.value = ""; // subtotaalInput = ""; } };
 <!doctype html> <html lang="nl"> <head> <script src="javascript-test-2.js" defer></script> <title>Test</title> <link rel="icon" href="javascript.ico" type="image/x-icon"> <link rel="stylesheet" href="default.css"> </head> <body> <div id="container"> <!-- BESTEL FORMULIER --> <h2>Bestelformulier</h2> <label for="groenten">Kies u groenten</label> <!-- <span id="selecteerAub" style="color: red;"></span> --> <span id="selecteerAub" class="fout">Verplicht te kiezen.</span> <select name="groenten" id="groenten" class="required"> <option id="defaultOption" value="" disabled selected hidden>Kies hier...</option> </select> <span id="kiesGroente"></span> </br> <!-- <span id="invoerAub" style="color: red;"></span> --> <span id="invoerAub" class="fout">Verplicht een getal in te voeren.</span> <label>Aantal</label> <input id="aantal" type="number" min="1" required/> <button type="submit" id="toevoegen">Toevoegen in mijn mandje</button> </br> <!-- Shopping cart --> <div id="winkelmandje"> <h2>Winkelmandje</h2> <div> <p>Totaal:</p><span id="totaalBerekenen"></span> </div> </div> <table id="table"> <tr> <th>Naam</th> <th>Aantal</th> <th>Subtotaal</th> </tr> <!-- JS will insert here new TR --> </table> </div> </div> </body> </html>

To solve your two questions you need to decide on a datatype for persisting the quantity and subtotal. There are many ways to do this.

Below, I simply added a quantity and subtotal key to each of the objects within the allGroenten array. You can rename these later.

Then, when someone submits your simple form, instead of adding a success of rows to the table, we are going to regenerate the entire tbody from the data source each time. To better facilitate this, I added and empty tbody to the html as well as moved the tr full of your headers into a thead element.

Then each time someone clicks the button, based on valid data, we grab the name and value and update only the quantity and subtotal for the relevant object. And while we are iterating through the array, we are rebuilding the table with updated data and finally we are updating the total.

See below with added comments:

 "use strict"; //Lijst met info van groeten. but add quantity and subtotal to persist data const allGroenten = [ { naam: "Bloemkool", prijs: 1.15, eenheid: "stuk", quantity: 0, subtotal: 0.0 }, { naam: "Chinese kool", prijs: 1.95, eenheid: "stuk", quantity: 0, subtotal: 0.0 }, { naam: "Wortelen", prijs: 0.99, eenheid: "kg", quantity: 0, subtotal: 0.0 } ]; // store currency to reuse const currency = "\€"; //DROPDOWN MENU INVULLEN MET DE OBJECTEN VAN ALLGROENTEN const select = document.getElementById("groenten"); for (let i = 0; i < allGroenten.length; i++) { const opt = allGroenten[i].naam; const el = document.createElement("option"); el.text = opt + " - " + currency + allGroenten[i].prijs + " /" + allGroenten[i].eenheid; el.value = allGroenten[i].prijs; el.dataset.naam = allGroenten[i].naam; el.id = [i] select.add(el); } // EVENT .onClick op Toevoeg button document.getElementById("toevoegen").onclick = function() { invoerAub.innerText = ""; let aantalCheck = document.getElementById("aantal"); let check = aantalCheck.value; selecteerAub.innerText = ""; let selecteerCheck = document.getElementById("groenten"); let checkSelect = selecteerCheck.value; if (check == false) { const invoerAub = document.getElementById("invoerAub"); invoerAub.innerText = "Aantal ingeven aub."; } else if (checkSelect == false) { const invoerAub = document.getElementById("selecteerAub"); invoerAub.innerText = "Selecteer u groeten aub."; } else { const naamInput = document.getElementById("groenten"); const naam = naamInput.options[naamInput.selectedIndex].text; const aantalInput = document.getElementById("aantal"); const addQuantity = aantalInput.value; // reset the tbody on each transaction const tbody = document.querySelector("tbody"); tbody.innerHTML = ''; // initialize totaal sum variable let totaal = 0.0; // updated quantity && subtotal and update DOM for (let i = 0; i < allGroenten.length; i++) { // update quantity and subtotal based on input if (naam.includes(allGroenten[i].naam)) { // ensure data type stays as Number allGroenten[i].quantity = +allGroenten[i].quantity + +addQuantity allGroenten[i].subtotal = allGroenten[i].quantity * allGroenten[i].prijs } // update subtotal and total for all const tr = tbody.insertRow(); const naamTd = tr.insertCell(); naamTd.innerText = allGroenten[i].naam; const aantalTd = tr.insertCell(); aantalTd.innerText = allGroenten[i].quantity; const subtotaalTd = tr.insertCell(); subtotaalTd.dataset.subPrijs = allGroenten[i].subtotal; subtotaalTd.innerText = allGroenten[i].subtotal.toFixed(2); totaal += allGroenten[i].subtotal } // show total const totaalBerekenen = document.getElementById("totaalBerekenen"); totaalBerekenen.innerText = currency + totaal.toFixed(2) } };
 <div id="container"> <!-- BESTEL FORMULIER --> <h2>Bestelformulier</h2> <label for="groenten">Kies u groenten</label> <!-- <span id="selecteerAub" style="color: red;"></span> --> <span id="selecteerAub" class="fout">Verplicht te kiezen.</span> <select name="groenten" id="groenten" class="required"> <option id="defaultOption" value="" disabled selected hidden>Kies hier...</option> </select> <span id="kiesGroente"></span> <br/> <!-- <span id="invoerAub" style="color: red;"></span> --> <span id="invoerAub" class="fout">Verplicht een getal in te voeren.</span> <label>Aantal</label> <input id="aantal" type="number" min="1" required/> <button type="submit" id="toevoegen">Toevoegen in mijn mandje</button> <br/> <!-- Shopping cart --> <div id="winkelmandje"> <h2>Winkelmandje</h2> <div> <p>Totaal:</p><span id="totaalBerekenen"></span> </div> <br/> <table id="table"> <thead> <tr> <th>Naam</th> <th>Aantal</th> <th>Subtotaal</th> </tr> </thead> <tbody> <!-- JS will insert here new TR --> </tbody> </table> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM