0

I am making a calculator which will work as follows:
the user will put his calculation in a textbox eg: 2+4+5; then the whole string will be converted to integer and calculate the numbers and display the result:11;. My code is as follows:

Script:

function solve() {  
    problem = parseInt(document.getElementById('prob'));   
    ans = document.getElementById('ansspace');  
    ans.innerHTML = problem  
}  

HTML:

<input type="text" id="prob">  
<br>  <input type="button" id="add" value="Add" onclick="solve()">  <br>  
<p id='ansspace'></p>
2
  • 1
    What is your question? If it's about how to evaluate the string, this has been asked before. Commented Jun 9, 2012 at 17:08
  • 1
    Brace yourselves, eval answers are coming. Commented Jun 9, 2012 at 17:14

3 Answers 3

2

You can use eval() to do calculation, but beware of security issues. eval is not recommended as user can execute his code from page. Otherwise, use regex to parse the content or use regex to validate if input values are safe to use with eval

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

1 Comment

Code injection is a non-issue in this case as the user could also do so by running a javascript: url in the address bar, using his browser's developer tools, etc. As long as he cannot share a link to the calculation (i.e. get other users to execute whatever he entered) this is not a big problem. Using try..catch to do proper error handling is fine for this.
1

Using jQuery as simple as:

$('#add').on('click', function() {
    var solution = eval($('#prob').val());
    $('#ansspace').html(solution);
});​​​​​

See a live example here

3 Comments

While I'm all pro-jQuery and you do answer the question I don't think it was really necessary to rewrite his code to use jQuery. By the way, .on('click' ...) is the preferred way to go since jQuery 1.7.
Thanks for the heads up! I did not know the standard had changed :)
thanks for your answer but i dont want to use jquery and i dont know any programming of it, can you give the answer in Javascript
0

There's really no easy way to make an calculator but for your code to work you can use eval:

function solve() {  
  var problem = document.getElementById('prob').value;   
  var ans = document.getElementById('ansspace');   
  ans.innerHTML = eval(problem);  
}  

1 Comment

Please do not create unnecessary globals. Use var to make variables local.

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.