0

当仅单击“添加”按钮时,我试图调用两个函数。我遇到的问题是 calculate_balances 函数中的最后四个文本框没有输出它们的变量。

var $ = function (id) {
    return document.getElementById(id);
}




// Declare Arrays to store information from Inputs //
var transactions = [];
transactions[0] = []; // holds date
transactions[1] = []; // holds transaction type
transactions[2] = []; // holds amount

// Function to print results to text area //
var update_results = function () {
    var list = ""; // string variable to build output //    
    // check to see if arrays are empty //
    if (transactions[0].length == 0) {
        $("results").value = "";
    } else {
        list = "";
    // for loop to cycle through arrays and build string for textarea output // 
        for (var i = 0; i < transactions[0].length; i++) {
        list += transactions[0][i] + "     " + transactions[1][i] + "      " + transactions[2][i] + "\n";
        }
    // display results //
    $("results").value = list;
    }


}
// function to gather inputs //
var add_transaction = function () {
    $("add").blur();
    transactions[0][transactions[0].length] = $("date").value;
    transactions[1][transactions[1].length] = $("transType").value;
    transactions[2][transactions[2].length] = parseFloat( $("amount").value);
    update_results();
    calculate_balances();


}

// function for Calculations //
 var calculate_balances = function () {

    var startBal = 2000.00;
    var ttlDeposits = 0;
    var ttlWithdrawals = 0;
    var endBal = startBal;

    if (transactions[1][transactions[1].length] == "deposit")
    {
        ttlDeposits += transactions[2][transactions[2].length];
        endBal += ttlDeposits;
    }
    if (transactions[1][i] == "withdrawal")
    {
        ttlWithdrawals += transactions[2][transactions[i]];
        endBal -= ttlWithdrawals;
    } 

    $("balStart").value = parseFloat(startBal);
    $("ttlDeposits").value = parseFloat(ttlDeposits);
    $("ttlWithdrawals").value = parseFloat(ttlWithdrawals);
    $("balEnd").value = parseFloat(endBal);

}  
window.onload = function () {
    $("add").onclick = add_transaction, calculate_balances;
    update_results();
}

谢谢你

4

1 回答 1

1

编辑:没有意识到 OP 没有使用 jQuery。您的 onclick 应如下所示:

$("add").onclick = function(){
    add_transaction();
    calculate_balances();
};

这里的其余部分用于 jQuery,这不是 OP 想要的。

要使用 jQuery 设置文本框的值,请使用 val() 方法:

$("balStart").val(parseFloat(startBal));

单击按钮时调用这两个方法:

$("add").click(function(){
   add_transaction();
   calculate_balances();
});
于 2013-03-04T21:00:00.530 回答