2013-03-18 45 views
1

我發現,是有幫助的幾個線程,但沒有直接回答我的問題,所以這裏的具體問題:jQuery的小費計算器 - 與基於文本區輸入變量的公式

磨練我有限的jQuery的技能,我創建拆分賬單/提示計算器,根據以下輸入計算點擊按鈕的金額:賬單總額,提示百分比,人數。

但是,當我點擊按鈕時沒有任何事情發生。這裏是jQuery代碼:

$(document).ready(function() { 
$('button').click(function(){ 
var Total = $('.Total').val(); 
var Tip = $('.Tip').val(); 
var NumberOfPeople = $('.NumberOfPeople').val(); 
var AdjTotal = (((Tip/100)*Total)+Total).toFixed(2); 
var Result = (AdjTotal/NumberOfPeople).toFixed(2); 
if(isNaN(AdjTotal)) { 
    $('.result').remove(); 
    $('.error').remove(); 
    $('.price').append('<p class="error">Please enter valid numbers into the above fields.</p>'); 
} 
else { 
    $('.error').remove(); 
    $('.result').remove(); 
    $('.price').append('<p class="result">Your total is $' + AdjTotal + ' ' + 'and each person owes: $' + Result + '.</p>'); 
} 
}); 
}); 

和HTML:

<!DOCTYPE html> 
<html> 
    <head> 
     <link rel="stylesheet" href="style.css" /> 
     <script src='script.js'></script> 
     <title>Split the Bill</title> 
    </head> 
    <body> 
     <div class="header"> 
      <h1>Split the Bill</h1> 
     </div> 
     <div> 
      <table> 
       <tbody> 
        <tr> 
         <td align="right"> 
          Bill Total: $ 
         </td> 
         <td text-align="left"> 
          <input class="Total" type="text" name="Total"> 
         </td> 
        </tr> 
        <tr> 
         <td align="right"> 
          Tip Percentage: 
         </td> 
         <td text-align="left"> 
         <input class="Tip" type="text" name="Tip"> % 
         </td> 
        </tr> 
        <tr> 
         <td align="right"> 
          Number of People: 
         </td> 
         <td colspan=3> 
          <input class="NumberOfPeople" type="text" name="Number of People"> 
         </td> 
        </tr> 
        <tr> 
         <td colspan=4 align="right"> 
          <button>Calculate</button> 
         </td> 
        </tr> 
       </tbody> 
      </table> 
     </div> 
     <div class="price"> 
     </div> 
    </body> 
</html> 

感謝您的幫助!

+0

您正在嘗試當你發現自己說:「什麼也沒有發生使用類選擇時,真正的元素應該由它的name屬性 – 2013-03-18 15:30:58

+0

引用「,試着在你的代碼中插入'console.warn('test')'消息或警報,看看它們是否被觸發。 – 2013-03-18 15:31:13

回答

1

的問題是這一行:

var AdjTotal = (((Tip/100)*Total)+Total).toFixed(2); 

總計是一個字符串。你需要迫使它是一個數字:

var AdjTotal = (((Tip/100)*Total)+Total/1).toFixed(2); 

http://jsfiddle.net/59WXX/