Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an eval name is undefined

I have a form that is basically a calculator. you can type an equation in and it will evaluate it. I also have 2 memory fields(text boxes named m1 and m2) where you can type something in and it will hold that value and then when you are typing an expression in the first box, you can reference m1 or m2 in your equation and it will evaluate using the numbers you entered in the memory fields.

The problem is if you try to reference m1 or m2 in your equation and the text boxes are blank, You get an undefined error.

I've been spinning my wheels for hours to try and put some sort of check that if the equation is evaluated to undefined, just show a pop up box. I need this in raw javascript. any help is appreciated.

function displayResult(thisElement)
{
    thisElement.value = eval(thisElement.value); <!-- this line throws the error if you use m1 and no m1 is defined, m2 and no m2 is defined, etc -->
    if(!(thisElement.value>0))
    {
        thisElement.value=0;
    }
}

function mem(v) 
{
    v.value = eval(v.value);
    eval(v.name+"="+v.value);
}

<input id="calcFormula" name="calculate" size="40" />
<input type="submit" value="Calculate" onclick="displayResult(this.form.calculate);" />

<input name="m1" id="m1" size="12" onchange="mem(this);" value="0" />
<input name="m2" id="m2" size="12" onchange="mem(this);" value="0" />
like image 316
Catfish Avatar asked Jun 28 '12 21:06

Catfish


1 Answers

I can think of three solutions:

  1. You can make an assumption that empty m1/m2 means 0, so there will never be an undefined value. This really simplifies things.
  2. You can use regexp to check first for any occurrence of m1 or m2 in the equation and if it exists then check if is undefined.
  3. But the best method is to use try...catch.

Try/Catch Example:

try {
    eval('12+3+m1');
} catch (e) {
    alert(e.message);
}
like image 174
Kamil Dziedzic Avatar answered Oct 24 '22 05:10

Kamil Dziedzic