Ad

How Do I Lookup An Operator Value In Html, Set It As A Var And Use It In A Javascript Function?

- 1 answer

i have a span which reads 1+2= :

<span id="num1">1</span> <span id="op">+</span> <span id="num2">2</span> =

i have a javascript function:

    $(document).ready(function() {

      var num1 = parseInt($("#num1").text());
      var op = $("#op").text();
      var num2 = parseInt($("#num2").text());
      console.log(num1 + op + num2);          //doesnt work

    });

this is purely for experimental reasons, but how would i go about adding 1+2 using the operator listed in my html? can i set an operator to a var and use it somehow?

my thought was to do console.log(num1 + op + num2); but that doesnt do anything

Ad

Answer

Do not use eval() as it is evil. Kindly try to mix and match the operators.

$(document).ready(function() {
  var num1 = parseInt($("#num1").text());
  var num2 = parseInt($("#num2").text());
  var op = $("#op").text();
  switch (op) {
    case "+":
      console.log(num1 + num2);
      break;
    case "-":
      console.log(num1 - num2);
      break;
    case "/":
      console.log(num1 / num2);
      break;
    case "*":
      console.log(num1 * num2);
      break;
  }
});
Ad
source: stackoverflow.com
Ad