简体   繁体   中英

Calculator on JavaScript(simple)

In the text field, you need to specify the values ​​and count them by the button. I do not understand why not think so? You need to implement it in principle through a switch but I can not understand why operations are not counted: +, -, *, /

<p>
  <label for="text1">FirstNum</label> 
  <input type="text" id="text1"><br>
  <label for="operation">Operation</label> 
  <input type="text" id="operation"><br>
  <label for="text2">SecondNum</label> 
  <input type="text" id="text2"><br>
  <label for="text3">Result</label> 
  <input type="text" id="text3"><br><br>
  <input type="button" value="ClickResult" onclick="Calc()">
</p>

<script>

  function Calc(operation) {
    //var op;
    switch(operation) {
      case '+':
        text3.value = text1.value + text2.value;
        break;
      case '-':
        text3.value = text1.value - text2.value;
        break;
      case '/':
        text3.value = text1.value / text2.value;
        break;
      case '*':
        text3.value = text1.value * text2.value;
        break;
    }      
 }

</script>

You need to get the values of textbox like so:

   var text1 = document.getElementById('text1').value;

But the value you get is in string format, so you need to convert it into int or float so you have to typecast it into int or float like so:

   text1 = parseFloat(text1);

and then give out the value in the result box like so:

document.getElementById('text3').value = result of the calculation

or another way is:

var result = document.getElementById('text3');
result.value = result of computation

 <p> <label for="text1">FirstNum</label> <input type="text" id="text1"><br> <label for="operation">Operation</label> <input type="text" id="operation"><br> <label for="text2">SecondNum</label> <input type="text" id="text2"><br> <label for="text3">Result</label> <input type="text" id="text3"><br><br> <input type="button" value="ClickResult" onclick="Calc()"> </p> <script> function Calc() { var text1 = document.getElementById('text1').value; var text2 = document.getElementById('text2').value; var operation = document.getElementById('operation').value; var text3 = document.getElementById('text3'); text1 = parseFloat(text1); text2 = parseFloat(text2); //var op; switch(operation) { case '+': text3.value = text1 + text2; break; case '-': text3.value = text1 - text2; break; case '/': text3.value = text1 / text2; break; case '*': text3.value = text1 * text2; break; } } </script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM