如何从一个输入框在javascript中创建添加功能

时间:2017-02-26 08:02:02

标签: javascript jquery

我正在尝试制作JavaScript计算器。我想在JavaScript中创建简单的添加功能,但不知道如何构建该逻辑,需要别人帮助,并且在我的代码中存在一个输入文本字段。

代码包含输入按钮,现在我需要帮助。那么如何在JavaScript中添加函数呢?

function plus()
  {
      var textInputval=0;
      var textInputval1=2;
      var temp=0;
      textInputval = parseInt(document.getElementById('new').value);
      textInputval1 = parseInt(document.getElementById('new').value);
      temp = textInputval + textInputval1;
      console.log(textInputval);
      console.log(textInputval1);
  }
<div id = "cal-container">
    <form name="calculator">
      <input type="text" name="answer" value="" id="new">
      <br>
      <input type="button" value=" 1 " onclick="one()" />
      <input type="button" value=" 2 " onclick="two()" />
      <input type="button" value=" 3 " onclick="three()" />
      <input type="button" value=" + " onclick="plus()" />
    </form>
</div>

1 个答案:

答案 0 :(得分:0)

 function action(method) {
          var a = parseInt(document.getElementById("num1").value);
          var b = parseInt(document.getElementById("num2").value);
          var result = null;

          switch (method) {
            case 'add':
              result = a + b;

              break;
            case 'subtract':
              result = a - b;
              break;
            case 'multiply':
              result = a * b;
              break;
            case 'divide':
              if (b != 0) {
                result = a / b;
              } else {
                alert('Can\'t divide by 0');

                return;
              }

              break;
          }

          if (result !== null) {

            document.getElementById("result").value = result;
          } else {

            document.getElementById("num1").value = "";
            document.getElementById("num2").value = "";
            document.getElementById("result").value = "";
          }
        }
<span style="margin-right:1px">Number 1 </span>
<input id="num1" type="number"></br>
<span style="margin-right:5px">Number 2</span><input id="num2" type="number"></br>
<span style="margin-right:29px">Result</span><input id="result" type="number"> </br>


<button id="add" onclick="action('add')">+</button>
<button id="subtract" onclick="action('subtract')">-</button>
<button id="multiply" onclick="action('multiply')">*</button>
<button id="divide" onclick="action('divide')">/</button>
<button id="clear" onclick="action('clear')">clear</button>