user2514231
user2514231

Reputation: 37

Calculation on a javascript input type=text

I have an input type= text that I take the value of to compare to another know value. When the user enters an integer or floating point number it works great. However, if the user enters a calculation say 12/297 or 12 + 9 I would like to perform the calculation and then compare the result to a known value. Any suggestions on how I would do this.

The input field is simply

<input type="text" id="A1">

The code that is getting the value as a float is:

parseFloat(document.getElementById("A1").value

I have tried just taking the value as a string and attempting to manipulate it but no luck. Also I tried tried parsing as a string on the operation sign and then applying the operation to each part of the string but that is a huge amount of work for a tiny issue so there has got to be a better solution.

Thanks

Upvotes: 0

Views: 584

Answers (3)

MarioDS
MarioDS

Reputation: 13073

Forget about eval, it's more trouble than it's worth.

You should parse the string and execute the mathematical expressions in the correct order, which can be quite a big algorithm depending on your needs. I'll leave the implementation up to you, but on a high level it would go about like this:

  1. Cleanup the input: remove all whitespace, it'll improve performance.
  2. Parse the string: loop over the characters and separate numbers from operators. You could end up with for example an array that maintains the order of everything.
  3. Apply the operands in correct order to the numbers left and right from it. Search the array of the previous step for * and / first etc. If you need support for ( and ), it'll make matters more complicated.

Simple example: [10, *, 10, /, 10] is your array. You search for * and /, and you find the first index 1 for *. You apply arr[1-1] * arr[1+1], the new result is [100, /, 10]. You continue , etc.

Of course there are a lot of possible approaches, but the bottom line is: it isn't a "tiny" issue, and "a lot of work" is very relative.

Upvotes: 1

Artem Petrosian
Artem Petrosian

Reputation: 2954

Since for this problem you should use eval, that isn't secure thing. But you can clean your entry string before this operation:

var expression = document.getElementById("A1").value;

var saveExpression = expression.replace(/[^-()\d/*+.]/g, '');

console.log(eval(saveExpression ));

Upvotes: 0

Gal Ziv
Gal Ziv

Reputation: 7372

you can use javascript eval function on the input value. this will evaluate the text as a javascript code. for example the next statement produces the value 7:

eval("2 + 5")

or for your example:

eval(document.getElementById("A1").value)

Upvotes: 1

Related Questions