So I just realized that I’m not that good when it comes to front-end development, so I decided to make a calculator app using only front-end.
All was going smoothly until I got to the part of actually making the buttons of my calculator do something. So I got to work and made a condition that if the clicked button was equal to the ‘C’ button (in case you don’t know, the ‘C’ button clears the calculator), then it would delete everything from the equation which is a read-only input tag. But this condition seems to not work because when I enter the ‘C’ button it actually adds to the input tag and not clear it.
Here’s my code:
const buttons = document.getElementById('buttons')
const input_field = document.querySelector('input[type="text"]') as HTMLInputElement
buttons?.addEventListener('click', function(event) {
const clicked_button = event.target as HTMLElement
if (clicked_button.tagName === 'BUTTON') {
if (clicked_button.textContent === 'C') {
input_field.value = ''
}
else {
input_field.value += clicked_button.textContent
}
}
})
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/@picocss/pico@latest/css/pico.classless.min.css">
<link rel="stylesheet" href="styles.css">
<title> Calculator </title>
</head>
<body>
<main class="container">
<h1> Calculator </h1>
<input type="text" readonly>
<div id="buttons">
<button> 7 </button>
<button> 8 </button>
<button> 9 </button>
<button id="eraser"> C </button>
<button> 4 </button>
<button> 5 </button>
<button> 6 </button>
<button class="calculation"> + </button>
<button> 1 </button>
<button> 2 </button>
<button> 3 </button>
<button class="calculation"> - </button>
<button> 0 </button>
<button class="calculation"> * </button>
<button class="calculation"> ÷ </button>
<button class="calculation"> % </button>
</div>
</main>
<script src="scripts.js"> </script>
</body>
</html>
By the way, yes, I have tsc’d my Typescript file.
2
Answers
I think the
textContent
value is going to be" C "
with a space on both sides. I would either add the space to the evaluation by doingclicked_button.textContent === ' C '
or trim it by doingclicked_button.textContent.trim() === 'C'
.The somewhat wrong thing you do is trying to use element text content as some sensefull value
I see you are a beginner, so go the easiest route there is – in-HTML handlers:
If you actuallu do need some data in HTML, use data-attributes