Javascript calculator problem
I'm having a little problem with a javascript calculator and I'm wondering if anyone could help me. The problem is that if the user inputs something with brackets but doesn't close them (i.e. only one bracket in the string), you get a javascript error.
http://www.meganjack.com/sa_1b1.html
How can I fix this? I'm thinking you could detect if there is only one bracket in the string and give an alert about it to the user. Kind of like validating a form. Sorry, I haven't done any real javascripting in ages.
Thanks!
druagord posted this at 17:05 — 22nd August 2003.
He has: 335 posts
Joined: May 2003
try this it should work but i didn't test it
function calcit() {
strExp = document.calc.shownum.value;
intopen =0;
intclose=0;
for(i=0;i<strExp.length;i++)
{
if(strExp.charAt(i)=='(')
{
intopen++;
}
else
{
if(strExp.charAt(i)==')')
{
intclose++;
}
}
}
if(intclose!=intopen)
{
document.calc.shownum.value ="error";
return;
}
if (document.calc.exp.value == "x") {
document.calc.shownum.value = eval(document.calc.shownum.value);
}
else {
document.calc.shownum.value = eval('Math.pow(' + document.calc.exp.value + ',' + document.calc.shownum.value + ')');
document.calc.exp.value = "x";
}
}
IF , ELSE , WHILE isn't that what life is all about
Megan posted this at 17:21 — 22nd August 2003.
She has: 11,421 posts
Joined: Jun 1999
That seems to work! Thanks a lot!
But, another problem - an error occurs when the user tries to put in more than one operator (i.e. 9+*). Any way to fix that too? I'm trying to figure out what you did there but it's a little bit beyond me I've tried looking for a different script but I can't seem to find one with the xy function. I might just decide to take out the calculator (seeing as how the users probably have a real one sitting on their desks anyway).
Megan
Connect with us on Facebook!
druagord posted this at 18:00 — 22nd August 2003.
He has: 335 posts
Joined: May 2003
if you can wait until monday i'll probably find an answer but i' a bit busy now sorry
Megan posted this at 18:01 — 22nd August 2003.
She has: 11,421 posts
Joined: Jun 1999
Don't worry about it - it was good of you to do that much already
Megan posted this at 19:03 — 22nd August 2003.
She has: 11,421 posts
Joined: Jun 1999
Nevermind, we decided to just take out the calculators. Thanks so much for your help anyway
druagord posted this at 19:11 — 22nd August 2003.
He has: 335 posts
Joined: May 2003
that alright it's been a pleasure. In fact I'll probably do it anyway just for the fun of it
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.