0

I am creating an online calculator but I am having trouble when a user enters their equation in the text box I can get the equation evaluated and displayed in the console log but, I can't get it to replace the equation with the answer. If “=” is clicked, it should evaluate the equation in the textbox and replace the equation with the answer. This is what I have so far.

 const equalsButton = document.querySelector('input[value="="]').onclick = function(){
    var inputVar = document.querySelector('[name=equation]').value
   
    console.log(eval(inputVar));
    return false;
  }

2 Answers 2

2

Since you didn't provide your html code, and since you use eval - take a look on this demo for simple calculator:

let total = []; // this will hold the arguments 
const equalsButton = document.querySelectorAll('input'); // calculator buttons 
for (var i = 0; i < equalsButton.length; i++) { // iterate the buttons
    equalsButton[i].addEventListener('click', function() { // listen to click 
        document.querySelector('#result').textContent += this.value; // add the clicked value to the screen
        if (this.value === '=') { // if equal clicked - show result
            document.querySelector('#result').textContent = eval(total.join('')); // result would be calculated from the total array arguments
        }        
        else { // any other clicked buttons
            total.push(this.value); // would be add to the array that would be the result when '=' would be clicked
        }
    });
}   
<div id="result" style="font-size: larger;"></div>
<div>
    <input type="button" value="0">
    <input type="button" value="1">
    <input type="button" value="2">
    <input type="button" value="3">
    <input type="button" value="4">
    <br>
    <input type="button" value="5">
    <input type="button" value="6">
    <input type="button" value="7">
    <input type="button" value="8">
    <input type="button" value="9">
    <br>
    <input type="button" value="+">
    <input type="button" value="-">
    <input type="button" value="/">
    <input type="button" value="*">
    <input type="button" value="=">
</div>

Sign up to request clarification or add additional context in comments.

Comments

1

If you want the result to get replace the equation, then you could simply reset the input of equation with the equation's solution :

    inputVar = eval(inputVar);

2 Comments

Thank you, instead, I did this. document.querySelector('[name=equation]').value = eval(inputVar)
great i am glad to help By the way, doing document.querySelector('[name=equation]').value = eval(inputVar) is better than store it in inputVar and then re-assign it !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.