Question:
When I press the equal button on my calculator it pops up as “undefined” on the screen. I think it has something to do with JS. Can’t figure out what.
Repl link:
https://replit.com/@DanielleSavage/Calculator#app.js
(function() {
let screen = document.querySelector('.screen');
let buttons = document.querySelectorAll('.btn');
let clear = document.querySelector('.btn-clear');
let equal = document.querySelector('.btn-equal');
buttons.forEach(function(button) {
button.addEventListener('click', function(e) {
let value = e.target.dataset.num;
screen.value += value;
})
});
equal.addEventListener('click', function(e) {
if (screen.value === '') {
screen.value = "Please enter";
} else {
let answer = eval(screen.value);
screen.value = answer;
}
})
clear.addEventListener('click', function(e) {
screen.value = "";
})
})();
1 Like
Hey @DanielleSavage, welcome to the forums!
I’m not good w/ JS so you’ll have to wait for another member of the community to answer but you have a problem in your HTML too. You forgot the closing tag in the input from lines 15-16:
<form>
<input type="text" class="screen" </form> <!-- should be a > in between class="screen" and </form> -->
1 Like
Your issue is that you assigned all the buttons a data-num
attribute that you use to append to the screen value.
The equals button doesn’t have a data-num
attribute.
Thus, when the first event handler tries to append the value of its data attribute to the screen it appends undefined since the equals button doesn’t have one.
This can be solved by either excluding the equals button from the buttons.forEach
, or giving the equals button a data-num=""
attribute.
2 Likes
For extra functionality, on the event listener for the equal button, add an else if
statement that contains the following code:
else if (screen.value.includes("/0")) { screen.value = "Cannot divide by 0"; } else {...}
I did test this and it does work really well
Edit: I don’t know if I put a period in the else if statement, I probably did but I don’t think I did, so I just removed it
2 Likes