簡體   English   中英

如何使用JavaScript for HTML Form計算活動總計

[英]How to calculate active total using javascript for html form

我有一個HTML表單,希望在表單底部生成一個運行總計。 我也想做一些其他簡單的計算,但是我找不到關於使用javascript.I進行簡單計算的任何信息。我​​不希望有人為我做這件事,我只希望有人指出正確的方向,也就是如何創建函數將一個數量乘以一個價格乘以一個價格,然后再添加一個就可以形成一個總數。

粗略的例子:

 <input type="text" name="qty1" onchange=""> <input type="text" name="price1" onchange="something">
 <input type="text" name="qty2" onchange=""> <input type="text" name="price2" onchange="something">

總會是這樣

=(qty1*price1)+(qty2*price2)依此類推,提交時我想將此數字放在我的sql數據庫中

我希望這不難解釋。

我也想跳過沒有輸入的字段。

如果要使用jQuery,請按以下步驟操作:

HTML:

<div>
    <input type="input" class="qty" />
    <input type="input" class="price" />
</div>
<div>
    <input type="input" class="qty" />
    <input type="input" class="price" />
</div>
<div>
    <input type="input" class="qty" />
    <input type="input" class="price" />
</div>
Total: <span id="total"></span>

JavaScript的:

jQuery(function($) {

$(".qty, .price").change(function() {
    var total = 0;
    $(".qty").each(function() {
        var self = $(this),
            price = self.next(".price"),
            subtotal = parseInt(self.val(), 10) * parseFloat(price.val(), 10);
        total += (subtotal || 0);
    });
    $("#total").text(total);
});

});

基本上,只要價格或數量發生變化,就可以枚舉每個數量的輸入。 您可以通過找到價格類別的下一個同級來獲得價格值(假設您的價格字段位於數量字段之后,並且在文檔中處於同一級別)。 然后解析其值-parseInt()表示數量,parseFloat表示價格。 例如,由於js被“猜測”並且將接受十六進制值,因此10參數是將基數強制為10。 如果由於值不是數字而無法進行計算,則小計將為NaN。 我用0來“或”,所以我不嘗試將NaN加到總數中。 最后,我將結果放入總字段。

您說過要將總數保存在某個地方。 您需要使用PHP在服務器上執行此操作,不要從客戶端發布該值。 客戶端可能會欺騙客戶發布的任何值,無論是否為隱藏字段。 你不能相信它。 因此,從發布的字段在服務器上進行計算。

jsfiddle:

http://jsfiddle.net/nCub9/

這就是我過去經常計算的。 答案也是正確的,但對我來說,這對我簡單的想法來說太復雜了。 感謝InfinitiesLoop和其他所有人的意見

 <html>
 <head>
 <script>
 function calculate(){ 
 if(isNaN(document.formname.qty.value) || document.formname.qty.value==""){ 
 var text1 = 0; 
 }else{ 
 var text1 = parseInt(document.formname.qty.value); 
 } 
 if(isNaN(document.formname.Cost.value) || document.formname.Cost.value==""){ 
 var text2 = 0; 
 }else{ 
 var text2 = parseFloat(document.formname.Cost.value); 
 } 
 document.formname.textbox5.value = (text1*text2); 
 } 
 </script>
 </head>

 <body>
 <form name="formname">
 <input type="text" name="qty" onblur="calculate()"<br/>
 <input type="text" name="Cost" onblur="calculate()"<br/>
 <input type="text" name="textbox5">
 </form>
 </body>
 </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM