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" />
I can think of three solutions:
Try/Catch Example:
try {
eval('12+3+m1');
} catch (e) {
alert(e.message);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With