0

This is my html code:

<input id="R1" type="text" value="100">
<input id="R2" type="text" value="200">
<input id="formula" type="text" value="">
<input type="button" id="save" value="save">

Here the user enter formula value dynamically like R1+R2, (R1-R2)*100. I need to calculate final value using the formula.

Ex: If user enter value in formula field R1+R2; I need the result 300. How do I calculate the value dynamically?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Parthasarathi
  • 99
  • 1
  • 6
  • I did something like this a long time ago. Try parsing the current infix string to a prefix string using a stack, and then evaluate using the prefix evaluation. – Sameer Anand Aug 14 '15 at 09:00
  • Search for 'expression evaluator' libraries, like [this one](https://github.com/silentmatt/js-expression-eval/tree/master) – huysentruitw Aug 14 '15 at 09:13

5 Answers5

2

Check out this snippet, should work with any combo:

function calExpression() {
   var f = document.getElementById('formula');
   var inps = document.getElementsByTagName('input');
   var expression = f.value.toUpperCase();//' '+f.value.replace(/([-\/\+\(\)])/g,' $1 ')+' ';
   for (var i = 0; i < inps.length; i++) {
      if (inps[i].id && inps[i].type && inps[i].type.toLowerCase() === 'text') {
          expression = expression.replace(new RegExp('\\b'+inps[i].id+'\\b', 'ig'), inps[i].value);
      }
    }
    eval('f.value = '+expression+';');
}
<input id="R1" type="text" value="100">
<input id="R2" type="text" value="200">
<input id="formula" type="text" value="">
<input type="button" id="save" value="save" onclick="calcExpression()">
joyBlanks
  • 6,419
  • 1
  • 22
  • 47
  • Downvoted this answer first because it uses `eval()`, but converting the expression to uppercase is in fact a simple but clever idea to prevent executing other javascript code. – huysentruitw Aug 14 '15 at 09:46
  • Thanks appreciate that. I was upset took care of being dynamic still downvoted... ;) – joyBlanks Aug 14 '15 at 09:51
  • Downvoted this answer because you're not able to run real arithmetic expression as `(((R1+R2) - (R1*3)) + 1) / 2` for example .. :/ – Paul Boutes Aug 14 '15 at 10:00
  • @PaulBoutes good catch I added as a RegExp actually it was only getting one. Thanks – joyBlanks Aug 14 '15 at 10:12
  • Ok, you get same result as me. So i remove the downvote :) – Paul Boutes Aug 14 '15 at 10:17
  • Hi joy, thank you for the solution. The calculation part works good. However, When I calculate `R4+R10` the scripts replaces R10 with R1 eliminating 0 in R10. How do I find the exact match? – Parthasarathi Aug 14 '15 at 10:22
  • @Parthasarathi Actually you need a boundary as well. Added boundary `\bword\b` . Should replace R1 with R1 and R10 with R10 exact match code updated. – joyBlanks Aug 14 '15 at 11:31
0

You can use eval. This is the fastest and easiest solution, but you must be careful with it and check with regexp that formula has only R1, R2, (, ) and math operators in it.

Or (better solution) you can find a library to parse expressions, in example http://mathjs.org/docs/expressions/parsing.html

Gennady Dogaev
  • 5,902
  • 1
  • 15
  • 23
-1
<input type="button" id="save" value="save" onclick="return calculate()">

<script>
    function calculate() {
        var val1 = document.getElementById('R1').value;
        var val2 = document.getElementById('R2').value;

        var result = +val1 + +val2;
        document.getElementById('formula').value = result;
    }
</script>

Because a problem occures with "+" you have to use +val1 + +val2

Hearner
  • 2,711
  • 3
  • 17
  • 34
-1

Infix to Prefix Conversion Algorithm: Infix to Prefix Conversion

Prefix Evaluation Algorithm: Prefix Evaluation Algorithm

Use help from these links.

Community
  • 1
  • 1
Sameer Anand
  • 274
  • 2
  • 13
-1

You can use .eval() method which allow you to evaluates JavaScript code represented as a string. It's a really powerful method.

Then, you have to parse your formula. With this piece of code, you will be able to add expression like ((R1+R2) - (R1*3)) + 1 for example.

  function calculate(){
    var valid = true;

    var regex = /(?:[a-z$_][a-z0-9$_]*)|(?:[;={}\[\]"'!&<>^\\?:])/ig;

    var formula = document.querySelector('#formula').value;

    var R1 = parseInt(document.querySelector('#R1').value);

    var R2 = parseInt(document.querySelector('#R2').value);

    formula = formula.replace(/R1/g, R1).replace(/R2/g,R2);

    formula = formula.replace(regex, function (elm) {
      return Math.hasOwnProperty(elm)
      ? "Math."+elm
      : valid = false;
  });

  if (valid)
    alert(eval(formula));

  }

Then add onlick event on save button :

<input id="R1" type="text" value="100">
<input id="R2" type="text" value="200">
<input id="formula" type="text" value="">
<input type="button" id="save" value="save" onclick="calculate()">

Here is the Working Plunker

Paul Boutes
  • 3,285
  • 2
  • 19
  • 22