2012-11-16 44 views
0

所以我想添加一個產品,同時更新購物車中的總價格。如何使用javascript顯示和更新總價格?

$(".articel input[type='button']").click(function() {     
    var price = $(this).siblings("input[name='price']").attr("value"); 
    var quantity = $(this).siblings("input[type='number']").attr("value"); 

    if (quantity % 1 != 0) { 
     alert("You must add a whole number"); 
    } 
    else if (quantity <= 0) { 
     alert("You can not add a negative number or nothing"); 
    } 
    else { 
     var name = $(this).siblings("input[name='prodname']").attr("value"); 
     var ul = document.getElementById("buylist"); 
     var totalprice = quantity * price; 
     var prod = name + " x " + quantity + "= " + totalprice + "$"; 
     var el = document.createElement("li"); 
     el.innerHTML = prod; 
     ul.appendChild(el); 
    } 
}); 
}); 

這裏就是產品和totalprice補充說:

<h4>Shopping Cart</h4> 
<div id="buylist"> 
    <ul> 
    </ul> 
    <div id="totalprice"> 
     <h4>Total price:<h4> 
    </div> 
</div> 

<a href="#checkout" onClick="checkOut()" class="click" data-toggle="tab" id="form">Checkout</a> 
</div> 

在這裏,在那裏我將產品添加到購物車

<form class="articel"> 
    Quantity: <input type="number" style="width:30px;"><br> 
    Add to cart: <input type="button" class="btn"> 
    <input type="hidden" value="30" name="price"> 
    <input type="hidden" value="The walking dead" name="prodname"> 
</form> 
+0

那麼是什麼問題? – Chad

+0

所以它增加了一個產品和該產品的總價格。問題是,當我想添加一件產品時,購物車中所有產品的總價應該出現在購物車中產品的底部。有沒有簡單的方法來做到這一點? (或不簡單...) – JJeff

回答

2

也許我真的不明白。但是當產品或其數量發生變化時,您必須計算價格。我建議,你已經有了這兩項行動的事件。然後我會運行一個計算價格的函數。

現在它取決於您是否已經有固定價格或者還需要將其與數量相乘。循環產品並計算價格。

注:要選擇價格&數量我使用了代碼中實際沒有的選擇器。

function calculatePrice() { 
    var quantity, price, sum = 0; 
    //loop through product "blocks" 
    $('.articel').each(function() { 
     price = $(this).children('.price').val(); 
     quantity = $(this).children('.quantity').val(); 
     //Add price to sum if number 
     if (!isNaN(price) && !isNaN(quantity)) { 
      sum += price * quantity; 
     } 
    }); 
    //Update Price 
    $('#totalprice').html('<h4>Total price:' + sum + '</h4'); 
} 
0

形式之一如果添加了價格和數量到UL您可以輕鬆處理:

<ul> 
    <li data-quantity="X" data-price="Z">...</li> 
</ul> 

將此函數添加到JavaScript文件。

function calcTotal (ul) { 
    var newTotal = 0; 
    ul.find('li').each(function(i,e) { 
    var li = $(e); 
    newTotal += li.data('quantity') * li.data('price'); 
    }); 
} 

然後在你的代碼,那裏是最後的東西:

itemPrice = quantity * price; 
var prodDesc = name + " x " + quantity + "= " + itemPrice + "$";//same as it was. 
var newLi = $("<li>"); 
newLi.text(prodDesc).data('quantity', quantity).data('price', price); 
ul.append(newLi); 
var totalPrice = calcTotal(ul); 
$('#totalprice h4').text('Total Price: ' + totalPrice); 

或多或少就是這樣。

+0

謝謝,不知道如何添加newTotal,然後在每次添加新內容時更新它。 – JJeff

+0

我相信你會把pdjota的腳本放在它自己的函數中,然後在'add to cart'腳本中調用它 – VIDesignz

相關問題