0

Possible Duplicate:
Evaluating a string as a mathematical expression in javascript

I have written a snippet of code in javascript, for a prompt to appear when clicked. I want to be able to enter a simple math problem (i.e. 230/2) and have it output the answer, rather than the math problem I just entered. Your help will be much appreciated.

<!DOCTYPE html>
<html>
<body>


<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

<script type="text/javascript">
function myFunction()
{
var x;

var mathProblem=prompt("Enter your math problem","");

if (name!=null)
  {
  x = mathProblem;
  document.getElementById("demo").innerHTML = x;
  }
}
</script>

</body>
</html>
Community
  • 1
  • 1
user1139403
  • 81
  • 1
  • 8

1 Answers1

0

You can use eval() to compute it:

document.getElementById("demo").innerHTML = eval(x);

Here is how your code should be:

function myFunction()
{
  var mathProblem = prompt("Enter your math problem","");

  if (mathProblem)
  {
    document.getElementById("demo").innerHTML = eval(mathProblem);
  }
}

Or if you dont want to use eval() (not recommended usually), you can create small functions to do the computation like for adding, dividing, etc

Blaster
  • 9,414
  • 1
  • 29
  • 25
  • And what if the user starts typing `` in the prompt? – acme Jun 26 '12 at 09:18
  • It would also be possible to restrict `mathProblem` to containing only digits and valid maths operators, which may be sufficient in this trivial example. – Andrew Leach Jun 26 '12 at 09:22
  • You are right, it really depends on the complexity of the allowed input here. If it's only about simple adding, substracting, dividing or multiplying it should be fine to parse the input in a regex to remove unsafe characters. – acme Jun 26 '12 at 09:30