简单的Javascript计算器

时间:2014-10-12 19:43:53

标签: javascript html

我正在尝试学习Javascript,我觉得我对基础知识有一个很好的把握,但我遇到问题让它做我想要的事情......例如..我试图在html中创建一个简单的表单计算2个数字的总和..这里是我的html和javascript:

<head>
    <script type="text/javascript">
        function adder(a,b) {
            var a = document.getElementById('firstNum').value;
            var b = document.getElementById('secondNum').value;
            var numbers = new Array(a,b);
            var sum = 0;

            for (i=0; i < numbers.length; i++) {
                sum += parseInt(numbers[i]);
            }

            //this part i need help with
            document.getElementById('answer').write("First Number: " + a + " plus Second Number: " + b + " is " + sum).value; //this part i need help with
    </script>
</head>
<body>
    <form id="additionForm">
        A + B = C : <input type="text" id="firstNum" placeholder="A"> 
        + <input type="text" id="secondNum" placeholder="B">
        <input type="button" id="addBtn" value="Add" onClick="adder();">
        = <input type="text" id="answer" placeholder="C">
    </form>
</body>

我的问题是我不知道如何让javascript覆盖我的表单输入id = answer的value属性..或者如果我应该使用Jquery而是...提前感谢。

2 个答案:

答案 0 :(得分:3)

function adder() {
  var a = parseInt( document.getElementById('firstNum').value, 10);
   var b = parseInt( document.getElementById('secondNum').value, 10);
   var sum = a + b;

  //this part i need help with
  document.getElementById('answer').value = "First Number: " + a + " plus Second Number: " + b + " is " + sum).value; //this part i need help with
}

答案 1 :(得分:2)

如果您想在javascript中修改输入字段,只需设置value属性:

document.getElementById('answer').value = "First Number: " + a + " plus Second Number: " + b + " is " + sum;