2014-09-12 26 views
0

目前情況: 嘿大家好,我在這裏一敗塗地。我是Javascript和Jquery的新手,並試圖構建一個功能性捐款表單。我有三個文本框 - 每個標籤都是「Cart Item」。每個代表一個人可以捐贈的基金。該文本框的設置,以便他們可以輸入他們想要捐贈的金額。然後,在底部,有一個calculateSum函數可以計算三個文本框中的值。下面是我用來做代碼:單擊元素時從變量中減去?

的文本框:

<input type="text" id="donation" class="donation form-control" placeholder="0.00" onkeydown="return isNumber(event);" onkeypress="return validateFloatKeyPress(this,event);" maxlength="13"> 

總顯示在與ID#合計跨度標籤:

<span id="total" onchange="numbersWithCommas()">0.00</span> 

這裏是代碼使總功能的工作:

<script> 
$(document).ready(function(){ 

    //iterate through each textboxes and add keyup 
    //handler to trigger sum event 
     $(".donation").each(function() { 

     $(this).keyup(function(){ 
       calculateSum(); 
     }); 
     }); 

    }); 

function calculateSum() { 

     var sum = 0; 
     //iterate through each textboxes and add the values 
     $(".donation").each(function() { 

      //add only if the value is number 
      if(!isNaN(this.value) && this.value.length!=0) { 
       sum += parseFloat(this.value); 
      } 

     }); 
     //.toFixed() method will roundoff the final sum to 2 decimal places 
     $("#total").html(sum.toFixed(2).replace(/(^\d{1,3}|\d{3})(?=(?:\d{3})+(?:$|\.))/g, '$1,')); 
    } 
</script> 

我也添加了刪除項目/資金的「購物車」clicki選項將「X」放在右邊。用於完成該代碼:

<a href="#" class="dr" title="Remove item"><span class="glyphicon glyphicon-remove-circle"></span></a> 

<script> 
$('.dr').click(function() { 
    $(this).parent().parent().fadeOut(1000, function() { 
     $(this).remove(); 
    }); 
}); 
</script> 

你可以看到它在這裏工作:http://saulmarquez.com/test/cart-delete.html

問題: 如果我輸入一個文本框的值,然後從車中刪除該項目(使用右邊的X按鈕),該值不會從購物車的總額中減去。當它被刪除時,我需要從總數中減去它。

我真的不知道該怎麼去做。我認爲它必須是以下腳本的一部分:

<script> 
$('.dr').click(function() { 
    $(this).parent().parent().fadeOut(1000, function() { 
     $(this).remove(); 
    }); 
}); 
</script> 

我不太確定。就像我說的,我是這個東西的新手。在此先感謝您的幫助!

+0

FYI你有2個版本的jQuery加載的頁面上,請用1.4.4標籤在它 – charlietfl 2014-09-12 17:17:50

+0

^我會的,謝謝! – SAULMARQ 2014-09-12 17:36:28

回答

2

調用calculateSum功能後,您刪除元素

<script> 
$('.dr').click(function() { 
    $(this).parent().parent().fadeOut(1000, function() { 
     $(this).remove(); 
     calculateSum(); 
    }); 
}); 
</script> 
+0

+1這比我開始做實際減去價值要容易得多。 – Regent 2014-09-12 17:18:06

+0

工作完美!很簡單!謝謝! – SAULMARQ 2014-09-12 17:20:50