-1

So I have this bit of code for a calculator and it when I put something in the textbox, it only shows undefined. I need it when I put a mathematical expression like 1+1 it will show 2. You can see it in action in my website: G1blue.github.io/gencal.html

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="utf-8">
        <title>Calculator: General (Under maintenance)</title>
        <style>
            h1{
                font-size: 100px;
                margin: auto;

            }
            div {
                font-size: 100px;
                position: absolute;
                top: 150px;
            }

        </style>
    </head>
    <button><a href="index.html">Go to home</a></button>
    <body>
     <h1>Calculator: General</h1>
     <input oninput="varChange()" id="equation" type="number">
     <div id="answer"></div>
     <script>
       function varChange(){
        var equation = document.getElementById("equation").value;
        var answer = document.getElementById("answer");
        answer.innerHTML = new Function(equation)()
       }
       
       
       
     </script>
    </body>
</html>

How do you fix this?

G1blue
  • 11
  • 3

2 Answers2

2

The function you're in need of is eval().

eval('1+1');
// Output: 2

Or implemented in your code that would be:

var equation = document.getElementById("equation").value;
var answer = document.getElementById("answer");
answer.innerHTML = eval(equation);

For more on the eval() function, read the documentation.

Hao Wu
  • 17,573
  • 6
  • 28
  • 60
davidroseboom
  • 187
  • 10
  • No problem. If you found this answer helpful, please consider marking it as an accepted answer! – davidroseboom Sep 02 '21 at 01:34
  • 2
    Using eval is very dangerous, because this makes the site trivially easy to conduct XSS attacks on. I personally would recommend building a parser instead, which gives much more freedom. However, if you insist on `eval`, you should consider using a library such as `validator` to sanitize strings. – Kenneth Lew Sep 02 '21 at 01:46
  • @KennethLew is right. From a security point of view I would not recommend `eval()`... – davidroseboom Sep 02 '21 at 01:48
  • What are alternatives to eval()? – G1blue Sep 02 '21 at 02:02
  • For alternatives to `eval()` have a look into [this question](https://stackoverflow.com/questions/2029888/what-are-the-alternatives-to-eval-in-javascript). – davidroseboom Sep 02 '21 at 17:08
0

As noted, eval is not very secure. It'd be easy to say, "hey, it's on the client so what do I care." And, you might be right. But, depending on your exact use case, you could be opening your users up to cookie theft and all sorts of undesirable things.

If you really need to do this in production, you'll likely want to use a sandbox with Node. VM2 should give you what you need.

lmonninger
  • 831
  • 3
  • 13