Brian Johnson
Brian Johnson

Reputation: 11

Javascript Text Input Calculator

I am somewhat new to Javascript and I'm trying to make a basic calculator that has 3 text inputs, a 1st number text box, an operation textbox, and a second number textbox, but it doesn't print out the text when I click a button or use any other method to trigger the event. This is my code:

<html>
<script>
function calc()
{
    var D = "";
    var A = document.getElementById("num1").value;
    var B = document.getElementById("op").value;
    var C = document.getElementById("num2").value;
    if(B == "+")
    {
        D = A+C;
    }
    elseif(B == "-")
    {
        D = A-C;
    }
    elseif(B == "*")
    {
        D = A*C;
    }
    elseif(B == "/")
    {
        D = A/C;
    }
    document.getElementById("result").innerHTML = D;
}
</script>

<body>
    <input type="text" id="num1" name="num1" />
    <input type="text" id="op" name="op" />
    <input type="text" id="num2" name="num2" />
    <br />
    <input type="button" value="Solve" onclick="calc()" />

    <p id="result" name="r1">
        <br />
    </p>

</body>
</html>

Upvotes: 1

Views: 41681

Answers (6)

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Amanpreet singh</title>
</head>
<body>
    <center>
<table  cellpadding="10" cellspacing="10" style="font-size:2em">
    <tr><td>Number 1:</td>
        <td><input type="text" id="num1" name="num1" /></td>
    </tr>
    <tr><td>Number 2:</td>
        <td> <input type="text" id="num2" name="num2" /></td>
    </tr>
    <tr>
        <td>  <label for=" Operator"> Operator:</label></td>
        <td> <select name="Operator" id="op" name="op">
    <option value="+">Add</option> <option value="-">Subtract</option>
    <option value="*">Muliply</option><option value="/">Divide</option>
  </select></td>
    </tr>
    <tr><td colspan="2" align="cover">
   <center> <input type="button" value="Solve" onclick="calc()" />
</center></td>
</tr>
<tr><td colspan="2" style="text-align: center;"><p id="result" name="r1" ></p></td></tr>
</table></center>
<script type="text/javascript">
function calc() {
var D = "0";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = document.getElementById("num2").value;
if (B === "+")
{
D = parseInt(A)+parseInt(C); 
}
else if(B === "-")
{
D = parseInt(A)-parseInt(C);
}
else if(B === "*")
{
D = parseInt(A)*parseInt(C);
}
else if (B === "/")
{
D = parseInt(A)/parseInt(C);
}
document.getElementById("result").innerHTML = "Result is :"+D;
return false;
}
</script>
</body>
</html>

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Amanpreet singh</title>
    </head>
    <body>
        <center>
    <table  cellpadding="10" cellspacing="10" style="font-size:2em">
        <tr><td>Number 1:</td>
            <td><input type="text" id="num1" name="num1" /></td>
        </tr>
        <tr><td>Number 2:</td>
            <td> <input type="text" id="num2" name="num2" /></td>
        </tr>
        <tr>
            <td>  <label for=" Operator"> Operator:</label></td>
            <td> <select name="Operator" id="op" name="op">
        <option value="+">Add</option> <option value="-">Subtract</option>
        <option value="*">Muliply</option><option value="/">Divide</option>
      </select></td>
        </tr>
        <tr><td colspan="2" align="cover">
       <center> <input type="button" value="Solve" onclick="calc()" />
    </center></td>
    </tr>
    <tr><td colspan="2" style="text-align: center;"><p id="result" name="r1" ></p></td></tr>
    </table></center>
    <script type="text/javascript">
    function calc() {
    var D = "0";
    var A = document.getElementById("num1").value;
    var B = document.getElementById("op").value;
    var C = document.getElementById("num2").value;
    if (B === "+")
    {
    D = parseInt(A)+parseInt(C); 
    }
    else if(B === "-")
    {
    D = parseInt(A)-parseInt(C);
    }
    else if(B === "*")
    {
    D = parseInt(A)*parseInt(C);
    }
    else if (B === "/")
    {
    D = parseInt(A)/parseInt(C);
    }
    document.getElementById("result").innerHTML = "Result is :"+D;
    return false;
    }
    </script>
    </body>
    </html>

Upvotes: -2

AndrewJ.G
AndrewJ.G

Reputation: 11

I recommend using eval() If the user inputs "5+6" or "(9*3)/5" and you set that to a variable, eval() will parse and solve the problem!

Upvotes: 1

Cris
Cris

Reputation: 1

There is a way you can do it with a single input box:

function findOps(s) {
  for (var i = 0; i < s.length; i++) {
    if (s[i] == "+")
      return "+";
    if (s[i] == "-")
      return "-";
    if (s[i] == "*")
      return "*";
    if (s[i] == "/")
      return "/";
  }
}
var input = '';
function calc() {
  var dom = $("#input");
  input = dom.val();
  try {
    switch (findOps(input)) {
      case "+":
        var a = input.split("+");
        var x = parseFloat(a[0]);
        var y = parseFloat(a[1]);
        var res = x + y;
        if (!isNaN(res)) {
          setTimeout(function() {
            dom.val(res.toFixed(3));
            dom.get(0).setSelectionRange(0, 0);
          }, 150);

        }
        break;
      case "-":
        var a = input.split("-");
        var x = parseFloat(a[0]);
        var y = parseFloat(a[1]);
        var res = x - y;
        if (!isNaN(res)) {
          setTimeout(function() {
            dom.val(res.toFixed(3));
            dom.get(0).setSelectionRange(0, 0);
          }, 150);

        }
        break;
      case "*":
        var a = input.split("*");
        var x = parseFloat(a[0]);
        var y = parseFloat(a[1]);
        var res = x * y;
        if (!isNaN(res)) {
          setTimeout(function() {
            dom.val(res.toFixed(3));
            dom.get(0).setSelectionRange(0, 0);
          }, 150);

        }
        break;
      case "/":
        var a = input.split("/");
        var x = parseFloat(a[0]);
        var y = parseFloat(a[1]);
        var res = x / y;
        if (!isNaN(res)) {
          setTimeout(function() {
            dom.val(res.toFixed(3));
            dom.get(0).setSelectionRange(0, 0);
          }, 150);

        }
        break;
    }

  } catch (err) {
    alert("catched¡");
  }

}

Upvotes: 0

David Thomas
David Thomas

Reputation: 253506

I'd suggest the following (explanations commented in the code itself):

function calc() {
        /* finds out whether the browser uses textContent (Webkit, Opera, Mozilla...)
           or innerText (Microsoft) to set the text of an element/node */
    var textType = Node.textContent ? 'textContent' : 'innerText',
        /* uses parseFloat to create numbers (where possible) from the entered value
           if parseFloat fails to find a number (it's empty or nonsensical)
           then a 0 is used instead (to prevent NaN being the output). */
        num1 = parseFloat(document.getElementById('num1').value) || 0,
        num2 = parseFloat(document.getElementById('num2').value) || 0,
        // retrieves the result element
        result = document.getElementById('result');

    // switch is used to avoid lots of 'if'/'else if' statements,
    // .replace() is used to remove leading, and trailing, whitespace
    // could use .trim() instead, but that'd need a shim for (older?) IE
    switch (document.getElementById('op').value.replace(/\s/g,'')){
        // if the entered value is:
        // a '+' then we set the result element's text to the sum
        case '+':
            result[textType] = num1 + num2;
            break;
        // and so on...
        case '-':
            result[textType] = num1 - num2;
            break;
        case '*':
            result[textType] = num1 * num2;
            break;
        case '/':
            result[textType] = num1 / num2;
            break;
        // because people are going to try, give a default message if a non-math
        // operand is used
        default:
            result[textType] = 'Seriously? You wanted to try math with that operand? Now stop being silly.'
            break;
    }
}

JS Fiddle demo.

References:

Upvotes: 2

Frank Tudor
Frank Tudor

Reputation: 4534

I would have done things a bit differently, but to answer your question and just get your code working I did the following:

Here is your reworked code:

<html>
<script>
function calc(form) {

var D = "0";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = document.getElementById("num2").value;

if (B === "+")
{
D = parseInt(A)+parseInt(C); 
}
else if(B === "-")
{
D = parseInt(A)-parseInt(C);
}
else if(B === "*")
{
D = parseInt(A)*parseInt(C);
}
else if (B === "/")
{
D = parseInt(A)/parseInt(C);
}
document.getElementById("result").innerHTML = D;
return false;
}
</script>
<body>

<input type="text" id="num1" name="num1" />
<input type="text" id="op" name="op" />
<input type="text" id="num2" name="num2" />
<br />
<input type="button" value="Solve" onClick="calc(this)">

<p id="result" name="r1">
<br />
</p>

</body>
</html>

I used the parseint() because your expressions in your if statements were treating values like text.

Next we need to use === Three equals which says A is really equal to + or what ever the second input value is.

Third was the onclick, I did a (this) and feed back form as you can see in the line that says function calc.

For good measure I added a return false; to prevent form submission (but it will function without it).

Also like other posters stated it is else if and not elseif.

I hope this is helpful. Again, I would do things differently but got it working with some explanations.

Upvotes: 1

aquinas
aquinas

Reputation: 23796

It's else if not elseif. Also you need to use parseInt on A+C, otherwise it will treat your strings as...well, strings. You should have seen the elseif error in your browser. Are you using something like firebug? If you aren't, start. Let tools do the hard work for you.

Upvotes: 0

Related Questions