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:

        function Wprowadzanie(nacisnieto){
            var temp = document.getElementById('kalkulator_linia_2').textContent;
            temp = temp + nacisnieto;
            document.getElementById('kalkulator_linia_2').innerHTML = temp;
        }
        function Dzialanie(nacisnieto){
            var temp = document.getElementById('kalkulator_linia_2').textContent;
            if(temp!="") document.getElementById('kalkulator_linia_1').innerHTML = document.getElementById('kalkulator_linia_1').textContent + ' ' + temp + ' ' + nacisnieto;
            document.getElementById('kalkulator_linia_2').textContent = "";
        }
        function Rowna_Sie(){
            var dzialanie = document.getElementById('kalkulator_linia_1').textContent + ' ' + document.getElementById('kalkulator_linia_2').textContent;
            document.getElementById('kalkulator_linia_1').innerHTML = dzialanie + ' =';

            var wynik = 0;

            document.getElementById('kalkulator_linia_2').innerHTML = wynik;
        }

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:

<div class="klawiatura_przycisk" onclick="Wprowadzanie(1)">1</div>

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

<div class="klawiatura_przycisk" onclick="Dzialanie('+')">+</div>

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

<div class="klawiatura_przycisk" onclick="Rowna_Sie()";>=</div>

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:

var wynik = eval(dzialanie);

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