Skip to content
Advertisement

How to calculate equasion from text content of element?

I’m trying to write basic calculator in js (I’m learning) and so far i wrote something like this:

JavaScript

Function Wprowadzanie is activated when a button (div) with number is pressed and gets the content of the button (0,1,2,3,etc..). Example:

JavaScript

Same with function Dzialanie, it gets activated when button with +,-,* or / is pressed and gets content of that button (for example ‘+’). Example:

JavaScript

Function Rowna_Sie is activated when button with “=” is pressed.

JavaScript

I tried to make function “Rowna_Sie()” calculate the content of var “dzialanie” and save it to var “wynik”, but everything I tried didn’t want to work. Could you please show me how to correctly finish that function?

Advertisement

Answer

You could use the eval function, which treats its argument as javascript code and tries to execute it. There are huge security concerns when you do this, but because the string is being built by buttons like that, and because this looks like it’s just a project you’re doing for fun, it should be fine. The code you need is this:

JavaScript

I don’t speak the language you named things in so it’s a little hard to follow, and I may have made a small mistake in the snippet. The argument should be the string containing the equation the user has entered. So if they wanted to calculate 1+1, you need to do eval("1 + 1") to get the answer.

Advertisement