Search code examples
javascriptgetelementbyidmath.js

Transfer variables from javascript to math.js (getElementById())


I am trying to transfer a javascript variable to a math.js function. The variable (denexp) is obtained by getElementById as follows:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">

  <script src="https://unpkg.com/mathjs@6.2.2/dist/math.min.js"></script>

  <style>
    body {
      font-family: sans-serif;
    }
  </style>
</head>
<body>

  <canvas id=canvas1 width=1600 height=400></canvas>
  <canvas id=canvas2 width=800 height=400></canvas>

<table>
  <tr>
    <th>den</th>
    <th><input type="number" id="denid" value="1.0" min="0">&nbsp;</th>
  </tr>
</table>

  <script>

    const sim = math.parser()
    const denexp = document.getElementById("denid").value;
    sim.evaluate("G = denexp")  // Density

  </script>
</body>
</html>

It seems, however, that math.js cannot read denexp

I get the following error:

Uncaught Error: Undefined symbol denexp

Do you have any ideas?


Solution

  • In the string ("G = denexp") which you pass to evaluate, Math.js expects to find things like numbers, units and mathematical symbols only: 0.5, sin, sqrt, deg, etc. You are trying to pass the variable denexp by simply including it in the string, but "denexp" is not a symbol which Math.js understands. Instead you must append the value of denexp to the string:

    sim.evaluate("G = " + denexp)
    

    Or if your browser targets support template literals:

    sim.evaluate(`G = ${denexp}`)
    

    Alternatively, you can provide a scope for Math.js which will allow you to use any variables defined in the scope within expressions:

    var scope = {
      denexp: denexp
    }
    sim.evaluate("G = denexp", scope)
    

    This has the benefit that any variable assignments (such as G = here) will also be saved to the scope (though simply assigning one variable to another, as done in your example, is not very useful and probably not what you are aiming for).