Javascript在两个不同的函数中获得结果并将它们添加在一起

Javascript getting result in 2 different functions and Adding them together

本文关键字:结果 加在一起 函数 两个 Javascript      更新时间:2023-09-26

我得到了这2个不同的javascript函数sum和diff,他们有2个结果。问题是,我怎么能得到2函数的结果,并添加它们,并显示在另一个文本框。

function sum() {
      var basicpay = document.getElementById('basicpay').value;
      var overtime = document.getElementById('overtime').value;
      var regularholiday = document.getElementById('regularholiday').value;
      var specialholiday = document.getElementById('specialholiday').value;
      var allowanceday = document.getElementById('allowanceday').value;
      var others1 = document.getElementById('others1').value;
      var grosspay = document.getElementById('grosspay').value;
      var monthpay13 = document.getElementById('monthpay13').value;
        var result = 
        parseInt(basicpay) + 
        parseInt(overtime) +
        parseInt(regularholiday) +
        parseInt(specialholiday) +
        parseInt(allowanceday) +
        parseInt(others1) +
        parseInt(grosspay) +
        parseInt(monthpay13);

        if (!isNaN(result)) {
            document.getElementById('totalincome').value = result;
        }
        }

另一个函数在这里:

function diff() {           
        var absent = document.getElementById('absent').value;
        var tardiness = document.getElementById('tardiness').value;
        var sss = document.getElementById('sss').value;
        var pagibig = document.getElementById('pagibig').value;
        var philhealth = document.getElementById('philhealth').value;
        var cashadvances = document.getElementById('cashadvances').value;
        var withholdingtax = document.getElementById('withholdingtax').value;
        var others = document.getElementById('others').value; 
        var result =
        parseInt(absent) - 
        parseInt(tardiness) -
        parseInt(sss) -
        parseInt(pagibig) -
        parseInt(philhealth) -
        parseInt(cashadvances) -
        parseInt(withholdingtax) -
        parseInt(others);

        if (!isNaN(result)) {
            document.getElementById('totaldeductions').value = result;
        }
        }

我只是想减去总扣除和总收入,并将其显示到另一个文本框。提前感谢

将这个函数添加到Javascript的顶部:

function calculate() {
   document.getElementById('both').value = sum() + diff();
}

添加一个新的HTML元素来保存你的答案:

19.<input type="text" Placeholder="Both" id="both" />

将所有onkeyup更改为:

onkeyup="calculate();"

最后,你需要改变你的"var result =…"代码,否则它只在输入所有数字时才有效。

我建议你少做手工工作,让你的文本框自动绑定到变量。做一些这样的教程,你会发现它是多么容易:http://learn.knockoutjs.com/#/?tutorial=intro

在不修改函数的情况下,可以这样做:

window.onload = function() {
    document.getElementById('othertextbox').value = parseInt(document.getElementById('totalincome').value) - parseInt(document.getElementById('totaldeductions').value);
}

(将上述代码添加到Javascript中)