Javascript calculator problem

Megan's picture

She has: 11,421 posts

Joined: Jun 1999

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's picture

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's picture

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 Smiling 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).

druagord's picture

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's picture

She has: 11,421 posts

Joined: Jun 1999

Don't worry about it - it was good of you to do that much already Smiling

Megan's picture

She has: 11,421 posts

Joined: Jun 1999

Nevermind, we decided to just take out the calculators. Thanks so much for your help anyway Smiling

druagord's picture

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 Smiling

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.