From bb70e895fffbd622f61f34da841957b858fe9eb6 Mon Sep 17 00:00:00 2001 From: moepoi Date: Fri, 19 Nov 2021 12:41:39 +0700 Subject: [PATCH] Fix & Update bag --- public/js/bag.js | 39 ++++++++++++++++++++++++++++----------- 1 file changed, 28 insertions(+), 11 deletions(-) diff --git a/public/js/bag.js b/public/js/bag.js index f830e8d..24a375b 100644 --- a/public/js/bag.js +++ b/public/js/bag.js @@ -2,6 +2,7 @@ function add(product_id, price) { var inputCount = document.getElementById(product_id); inputCount.value++; document.getElementById(product_id + '-price').innerHTML = 'Rp ' + price * inputCount.value; + set_total_price(); addToBag(product_id); } @@ -10,6 +11,7 @@ function minus(product_id, price) { if (inputCount.value > 0) { inputCount.value--; document.getElementById(product_id + '-price').innerHTML = 'Rp ' + price * inputCount.value; + set_total_price(); removeFromBag(product_id); } } @@ -76,13 +78,28 @@ function removeFromBag(product_id) { } } +function set_total_price() { + let price = document.getElementsByClassName("price"); + let total_price = 0; + for (let i = 0; i < price.length; i++) { + total_price += parseInt(price[i].innerHTML.substr(3)); + } + document.getElementById("total-price").innerHTML = 'Rp ' + total_price; +} + function view_bag() { var bag = JSON.parse(localStorage.getItem("bag")); + let total_price = 0; var html = ''; for (var i = 0; i < bag.length; i++) { - jQuery.get('api/getProduct', { id: bag[i].product_id }, (data) => { - let current_bag = bag.filter( x => x.product_id == data[0].ID); + let request = new XMLHttpRequest(); + request.open('GET', `api/getProduct?id=${bag[i].product_id}`, false); + request.send(null); + + if (request.status === 200) { + let data = JSON.parse(request.responseText); + total_price += parseInt(data[0].PRICE * bag[i].quantity); html += `
@@ -98,28 +115,28 @@ function view_bag() {
+ onclick="minus('${bag[i].product_id}', '${data[0].PRICE}')"> - + + onclick="add('${bag[i].product_id}', '${data[0].PRICE}')">

-

Rp ${data[0].PRICE * current_bag[0].quantity}

- Remove +

Rp ${data[0].PRICE * bag[i].quantity}

+ Remove

`; - document.getElementById("view-bag").innerHTML = html; - }); + } } - document.getElementById("total-price").innerHTML = 'Rp -'; + document.getElementById("view-bag").innerHTML = html; + document.getElementById("total-price").innerHTML = 'Rp ' + total_price; } view_bag(); \ No newline at end of file