-3

I have a simple form in javascript. I'm going to calculate a formula.

I want to select elements by id and then detects operators and finally calculate final result.

<p>
  V1: <input id="v1" />
</p>
<p>
  V2: <input id="v2" />
</p>
<p>
  V3: <input id="v3" />
</p>
<p>
  V4: <input id="v4" />
</p>
<p>
  Fromula: <input id="f1" />
</p>
<p>
  <button id="doAction">
    Calculate
  </button>
</p>

Example expression is: (v1+v2)*v3-(v4-v1)/v2

Bahman Shafiei
  • 395
  • 5
  • 22
  • in future, post CODE, not images of code ... as for "what codes or library is required" ... the answer is ... *your code*, or *some* library that *your code* can use - this is not a code writing service, and requests for library recommendations are off topic – Bravo Apr 09 '22 at 05:58
  • 1
    [Please do not post images of code/error messages.](https://meta.stackoverflow.com/a/285557). Edit your question, add your code. – Don't Panic Apr 09 '22 at 06:06
  • Try and find information on `document.getElementById()` and experiment with it. Also make sure to convert the `.values` of the input fields into numeric values before adding them to other values using the `+` operator. – Carsten Massmann Apr 09 '22 at 07:18
  • What have you tried? SO isn't a code-writing service, and [you are expected to do a lot of research](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) and attempt to solve the problem yourself. If you don't know where to start, a quick search for "*javascript add input values*" shows some answers with code to get you started, have you tried that? Eg https://stackoverflow.com/questions/13540751/how-get-total-sum-from-input-box-values-using-javascript – Don't Panic Apr 10 '22 at 05:54
  • What `^` is in your context? – Nick Vu Apr 10 '22 at 05:54
  • 2^3=8. 2^1=2 2^2=4 3^2=9 – Bahman Shafiei Apr 10 '22 at 06:23

2 Answers2

0

You can use eval and automatic mapping by ids (no need to call getElementById) to have that implementation

doAction.addEventListener("click", () => {

  const formula = f1.value
    .replaceAll("v1", v1.value || 0)
    .replaceAll("v2", v2.value || 0)
    .replaceAll("v3", v3.value || 0)
    .replaceAll("v4", v4.value || 0)
  result.innerHTML = eval(formula)
})
<p>
  V1: <input id="v1" />
</p>
<p>
  V2: <input id="v2" />
</p>
<p>
  V3: <input id="v3" />
</p>
<p>
  V4: <input id="v4" />
</p>
<p>
  Formula: <input id="f1" />
</p>
<p id="result">

</p>
<p>
  <button id="doAction">
    Calculate
  </button>
</p>

But one thing you need to be aware of, eval is not safe 100%, if you don't protect your code properly, somebody may inject malicious scripts. Here is the sample case

eval("alert('Not safe')")

If you want to have a safer way, you need to have a function to convert strings to operators with numbers like this

Nick Vu
  • 14,512
  • 4
  • 21
  • 31
0

Finally I found this solution:

var doAction = document.getElementById('doAction');

doAction.addEventListener('click', (s, e) => {  
  var scope=expressionArray("(v1+v2)*v3-v4");
  var formula = document.getElementById('f1').value;
  const result = math.evaluate(formula, scope)
  console.log(result);
});
function expressionArray(init)
{
    var text="";
  var split_var = init.split(/[*-/+()]+/);
  var obj={};
  split_var.forEach((s,e)=>{    
    if(document.getElementById(s))
    {
        obj[s]=document.getElementById(s).value;
    }    
  });
  return obj;
}

https://jsfiddle.net/bshafiei/zyv7bsfd/51/

Bahman Shafiei
  • 395
  • 5
  • 22