-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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

No problem. If you found this answer helpful, please consider marking it as an accepted answer!
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.
@KennethLew is right. From a security point of view I would not recommend eval()...
What are alternatives to eval()?
For alternatives to eval() have a look into this question.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.