How can I make my calculator buttons change function after the first click?

0
6
Asked By CreativeCoder99 On

I'm building a simple calculator in HTML for a school project, and I want the buttons to behave differently based on user input. For instance, when I click '5', it should show up in the first box, then when I click '+', it should pop up in the second box, and finally when I hit '4', it should go in the third box. However, I'm running into an issue where pressing a number also shows it in the third box instead of just the first. Can anyone help me figure this out? Here's my code:

```html

Calculator

...
```

I'm using JavaScript for the functionality, and I think there's a problem with how I'm setting my variables. Any advice would be appreciated!

3 Answers

Answered By CodeWhisperer On

Another suggestion is to simplify your output. Instead of using separate boxes for the numbers and operators, consider just one box for display and manage the calculations internally. This might help eliminate some confusion in your logic!

Answered By NewbieCoder On

If you want to keep using separate boxes, make sure you reset your variables correctly after each input. You want to have a clear state for what the user has inputted and what each button should be doing next!

Answered By HelpMeCode7 On

Looks like your issue stems from using a single equal sign (`=`) for assignments instead of a triple equal sign (`===`) for comparisons. In your `if` statements, change something like `if (num1HasNumber = 2)` to `if (num1HasNumber === 2)` to make sure you're comparing rather than assigning a value. That's likely the reason the values are not appearing where you expect them to!

HelpfulHarry42 -

I updated my code based on that advice, and now it behaves a bit better! But I'm still struggling a bit, should I change anything else?

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.