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>
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Mahesh Bansod
  • 1,493
  • 2
  • 24
  • 42
  • 1
    What is your question? If it's about how to evaluate the string, [this has been asked before](http://stackoverflow.com/search?q=javascript+evaluate+mathematical+expression). – Felix Kling Jun 09 '12 at 17:08
  • 1
    Brace yourselves, `eval` answers are coming. – Alexander Jun 09 '12 at 17:14

3 Answers3

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

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
hungryMind
  • 6,931
  • 4
  • 29
  • 45
  • 2
    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. – ThiefMaster Jun 09 '12 at 17:19
1

Using jQuery as simple as:

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

See a live example here

jacktheripper
  • 13,953
  • 12
  • 57
  • 93
  • 1
    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. – ThiefMaster Jun 09 '12 at 17:21
  • Thanks for the heads up! I did not know the standard had changed :) – jacktheripper Jun 09 '12 at 17:23
  • 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 – Mahesh Bansod Jun 09 '12 at 17:35
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);  
}  
WojtekT
  • 4,735
  • 25
  • 37
  • Please do not create unnecessary globals. Use [`var`](https://developer.mozilla.org/en/JavaScript/Reference/Statements/var) to make variables local. – ThiefMaster Jun 09 '12 at 17:25