Javascript获得2个不同功能的结果并将它们添加到一起

时间:2014-07-19 11:07:52

标签: javascript html

我得到了这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;

        }
        }

我只想减去totaldeductions和totalincome并将其显示给其他文本框。提前谢谢

2 个答案:

答案 0 :(得分:0)

将此功能添加到您的Javascript顶部:

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

添加新的HTML元素以保留答案:

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

将您的所有onkeyup更改为:

onkeyup="calculate();"

最后,您需要更改&#34; var result = ...&#34;代码,否则仅在输入所有数字时才有效。

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

答案 1 :(得分:0)

无需修改功能,您可以这样做:

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

(将以上代码添加到您的Javascript中)