I'm a beginner trying to create an online calculator in JS. I made buttons, looped through them, and then created a function that looks to click and display numbers on the screen with innerHTML of the screen. but It is saying undefined. Here is the code.
var screen = document.getElementById("screen")
var allButtons = document.getElementsByClassName('buttons');
for (var i = 0; i < allButtons.length; i++) {
allButtons[i].addEventListener('click', pressButton)
}
function pressButton(event){
var numID = this.id; // activates ID for each button the event listener above
screen.innerHTML = numID;
};
One example of how you could do it:
const screen = document.getElementById("screen") const allButtons = document.getElementsByClassName('buttons'); Array.prototype.forEach.call(allButtons, (e) => e.addEventListener('click', () => screen.innerHTML += e.innerHTML));
<div id="screen"></div> <br><br> <div class="buttons">Button1 </div> <div class="buttons">Button2 </div> <div class="buttons">Button3 </div>
Did you add the id attribute to all the buttons you created? It is possible that it is saying undefined cause it can't find the id attribute.
<!DOCTYPE html>
<html>
<head>
<title>Online Calculator</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="calc.css">
</head>
<body>
<textarea id="screen" placeholder="0"></textarea>
<div class="buttonswrap">
<button id="num1" class= "buttons" value="1">1</button>
<button id="num2" class= "buttons" value="2">2</button>
<button id="num3" class= "buttons" value="3">3</button>
<button id="num4" class= "buttons" value="4">4</button>
<br>
<button id="num5" class= "buttons" value="5">5</button>
<button id="num6" class= "buttons" value="6">6</button>
<button id="num7" class= "buttons" value="7">7</button>
<button id="num8" class= "buttons" value="8">8</button>
<br>
<button id="num9" class= "buttons" value="9">9</button>
<button id="num0" class= "buttons" value="0">0</button>
<button id="plus" class= "buttons" value="+">+</button>
<button id="multiply" class= "buttons" value="*">*</button>
<br>
<button id="divide" class= "buttons" value="/">/</button>
<button id="minus" class= "buttons" value="-">-</button>
<button id="point" class= "buttons" value=".">.</button>
<button id="equals" class= "buttons" value="=">=</button>
</div>
<script type="text/javascript" src="calc.js"></script>
</body>
</html>
Here is my HTML
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.