2017-07-14 3 views
4

同じ製品IDを持つ製品を追加する場合は、数量を増やして新しい行を追加する必要があります。私はコメントを試みた。 jsスクリプトの下で確認してください。しかし、それはまだ動作していません。同じ製品IDを追加しても数量を増やさない

let Cart = []; 
 

 

 
function viewCart() { 
 

 
    let tr = document.createElement('tr'); 
 
    for (cart of Cart) { 
 
    tr.innerHTML = `<td>${ cart.id }</td> 
 
         <td>${ cart.desc }</td> 
 
         <td>${ cart.qty }</td> 
 
         <td>${ cart.price }</td> 
 
         <td>${ cart.qty * cart.price }</td>`; 
 

 
    } 
 
    cartsTable.appendChild(tr); 
 
} 
 

 
function AddtoCart(productid, description, quantity, price) { 
 
    let inputs = { 
 
    id: productid, 
 
    desc: description, 
 
    qty: quantity, 
 
    price: price 
 
    }; 
 
    Cart.push(inputs); 
 
    viewCart() 
 
}
<script src="script.js"></script> 
 

 
<input type="button" value="Laptop" onclick="AddtoCart('132','Macbook Pro', 1, 100000)" /> 
 
<input type="button" value="Phone" onclick="AddtoCart('456','Iphone 5S', 2, 20000)" /> 
 
<input type="button" value="Camera" onclick="AddtoCart('789','Nikon 3D00', 1, 40000)" /> 
 

 
<table border="1|1" id="cartsTable"> 
 
    <tr> 
 
    <th>Product ID</th> 
 
    <th>Product Description</th> 
 
    <th>Quantity</th> 
 
    <th>Price</th> 
 
    <th>Total</th> 
 
    </tr> 
 
</table>

+0

私の答えにupvoteをいただければ幸いです:) – Erazihel

+0

私はすでにupvoted。ありがとうございますErazihel – Joseph

+0

あなたは答えを受け入れましたが、upvotedしていません。とにかく、私は助けることができてうれしいです。 – Erazihel

答えて

1

私はあなたがキーとしてproductidを使用する代わりにarrayobjectを使用することをお勧めします。

const cart = {}; 
 

 
function AddtoCart(productid, description, quantity, price) { 
 
    if (cart[productid]) { 
 
    cart[productid].qty += quantity; 
 
    } else { 
 
    cart[productid] = { 
 
     id: productid, 
 
     desc: description, 
 
     qty: quantity, 
 
     price: price 
 
    }; 
 
    } 
 
    
 
    viewCart(cart); 
 
} 
 

 
function viewCart() { 
 
    let tbody = document.getElementById('cartsBody'); 
 
    tbody.innerHTML = ''; 
 
    Object.values(cart).forEach(content => { 
 
    tbody.innerHTML += `<td>${ content.id }</td> 
 
         <td>${ content.desc }</td> 
 
         <td>${ content.qty }</td> 
 
         <td>${ content.price }</td> 
 
         <td>${ content.qty * content.price }</td>`; 
 

 
    }); 
 
}
<script src="script.js"></script> 
 

 
<input type="button" value="Laptop" onclick="AddtoCart('132','Macbook Pro', 1, 100000)" /> 
 
<input type="button" value="Phone" onclick="AddtoCart('456','Iphone 5S', 2, 20000)" /> 
 
<input type="button" value="Camera" onclick="AddtoCart('789','Nikon 3D00', 1, 40000)" /> 
 

 
<table border="1|1" id="cartsTable"> 
 
    <thead> 
 
    <tr> 
 
     <th>Product ID</th> 
 
     <th>Product Description</th> 
 
     <th>Quantity</th> 
 
     <th>Price</th> 
 
     <th>Total</th> 
 
    </tr> 
 
    </thead> 
 
    <tbody id="cartsBody"> 
 
    </tbody> 
 
</table>

関連する問題