jQuery Tip Calculator - 基于TextArea输入的变量公式

时间:2013-03-18 15:26:44

标签: jquery variables user-input validation jquery-calculation

我找到了一些有用的帖子,但没有直接回答我的问题,所以这里有具体的问题:

为了磨练我有限的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> 

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

问题在于这一行:

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

Total是一个字符串。你需要强迫它成为一个数字:

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

http://jsfiddle.net/59WXX/