2012-09-20 60 views
2

我已經構建了一個腳本來添加數量/單位並生成顯示銷售稅的總計。從計算的總和中減去一個整數

在計算並添加GST(10%銷售稅)之前,如何讓此計算器識別#discount並將其從總額中減去?

此外,頁面加載時是否可以生成總數?用戶不必按「生成總計」按鈕?

HTML

<ul> 
<li> Item 1 (<input type="text" name="others" size="4" value="5" readonly="readonly" class="readonly_field"/> units)</li> 
<li> Item 2 (<input type="text" name="others" size="4" value="1" readonly="readonly" class="readonly_field"/> units)</li> 
<li> Item 3 (<input type="text" name="others" size="4" value="3" readonly="readonly" class="readonly_field"/> units)</li> 
</ul> 


<input type="button" value="Generate Total" onclick="total()" /><br><br> 

Discount <input type="text" id="discount" name="discount" value="500"/><br><br> 

Total Units: <input type="text" id="units_total" name="units_total" readonly="readonly" /><br> 
Sub Total: <input type="text" id="sub_total" name="sub_total" readonly="readonly" /><br> 
Includes GST: <input type="text" id="gst_total" name="gst_total" readonly="readonly" /><br> 
Total: <input type="text" id="g_total" name="g_total" readonly="readonly" /> 

JS

function total(){ 
var total_value = 0; 
var all_others = document.getElementsByTagName("input"); 

for(var i=0; i<all_others.length; i++){ 
if(all_others[i].type!="text" || all_others[i].name!="others"){ 
    continue; 
} 
total_value += parseFloat(all_others[i].value); 
} 

document.getElementById("units_total").value = (total_value).toFixed(1); 

document.getElementById("sub_total").value = ((total_value) *100).toFixed(2); 

document.getElementById("g_total").value = (((total_value * 10/100) + total_value) * 100).toFixed(2); 

document.getElementById("gst_total").value = ((total_value * 10/100) * 100).toFixed(2); 
} 

回答

1

首先,讓你的函數來執行的窗口負載,在負載情況下把它包裝:

window.onload = function() { 
    total(); 
} 

其次,要讓它在打折的身影,你只需要修改可變幾次,但隨後相加在一起的時候,請確保您有.parseFloat()解析它們:

if (document.getElementById('discount').value != '') { 
    var discount = document.getElementById('discount').value; 
} 
else { 
    var discount = 0; 
} 
var sub_total = (((total_value) * 100).toFixed(2) - discount).toFixed(2); 
var gst = ((total_value * 10/100) * 100).toFixed(2); 

document.getElementById("sub_total").value = sub_total; 

document.getElementById("gst_total").value = gst; 

document.getElementById("g_total").value = (parseFloat(sub_total) + parseFloat(gst)).toFixed(2); 

DEMO

+0

完美,謝謝。 –

0

首先,我建議你進行驗證和計算,包括服務器端和客戶端。第一個確保安全性,第二個提高UI的響應性。

說的是,你最好引入幾個支持變量並對它們進行計算。您應該使用getElementById從您感興趣的元素中獲取價值,並將其存儲在變量中。 然後,您應該對這些變量執行計算,並最終將結果放入要用於將它們顯示給用戶的元素中。

要在頁面加載時執行操作,請看this