0

I have been wondering if is possible to use a HTML <input id="in"> (which I could enter lets say 25 / 6 * 3) and output the mathematical evaluation with Javascript, I have written up something which very understandably did not work, would there be any way to make it work?

function go() {
    var x = $("#in").val();
    alert(parseInt(x))
}

Your answers are much appreciated

4
  • 2
    Your question is not very clear. What does #in contain? Commented Feb 10, 2014 at 15:41
  • Please provide me code at fiddle Commented Feb 10, 2014 at 15:41
  • 1
    I'd think eval() would do it. jsfiddle.net/j08691/Vajh4 Commented Feb 10, 2014 at 15:44
  • I'd use eval, but first make sure it isn't dangerous. Commented Feb 10, 2014 at 16:14

3 Answers 3

2

Yes you can using the eval() function. Assuming you're input is going to take a value then you can simply call eval(myString) which should return the result.

For example if you execute the following:

alert(eval('3 + 4')); // alerts 7

Be wary though in that anything you do really shouldn't be saved as this could lead to javascript attacks if someone is able to submit some javascript that will run on someone elses browser.

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

Comments

0

Yes, it is possible to do what you're asking; you just have to use eval(). However, using eval() is not very safe. since this means that any JavasScript code inside #in will be evaluated, which is probably not what you want.

A better way to do this would be to write a parser to parse the mathematical expression and build a syntax tree and then evaluate that.

2 Comments

Well considering the person typing in the page would only be affecting their own browser, I don't see why any malicious results would be anyone's fault but their own.
@j08691 Of course; I wasn't implying maliciousness in this situation but merely alerting the OP to the caveats involved with the use of eval().
0

You can use the expression parser of math.js

alert(math.eval('3 + 4'));

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.