今天我試圖從<span>
價值和<input>
價值計算價值。然後,將結果放入<span>
。計算價格從<span>價值和<input>值
我已經試過這段代碼。這是我的html:
<td class="cart-product-price">
<span id="price" class="amount">19.99</span>
</td>
<td class="cart-product-quantity">
<div class="quantity clearfix">
<input type="button" value="-" class="minus" field="quantity">
<input type="text" id="quantity" name="quantity" value="2" class="qty" />
<input type="button" value="+" class="plus" field="quantity">
</div>
</td>
<td class="cart-product-subtotal">
<span id="total" class="amount"></span>
</td>
所以我想從<span id="price>
獲得價格值,從<input type="text" id="quantity" name="quantity">
獲得數量,並把結果<span id="total" class="amount"></span>
這是我的腳本代碼:
<script type="text/javascript">
var price = parseFloat($('#price').val()) || 0;
var qty = parseInt($('input[name=quantity]').val());
var total = price*qty;
$('#total').text(total);
</script>
注:我使用JQuery增加/減少數量(加上&減號按鈕)
我寫錯了嗎?
感謝
UPDATE
這是我的增加/減少JavaScript代碼:
<script type="text/javascript">
jQuery(document).ready(function(){
// This button will increment the value
$('.plus').click(function(e){
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$('input[name='+fieldName+']').val(currentVal + 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
// This button will decrement the value till 0
$(".minus").click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[name='+fieldName+']').val(currentVal - 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
});
</script>
您是否嘗試調試您的代碼?你有沒有看到你的JS函數中的價格和數量的價值?你在#total中得到了什麼結果? – James