Calculator display showing empty spaces instead of numbers

I'm currently working on developing a calculator, but I've hit a roadblock that I can't seem to overcome. The numbers aren't appearing in the calculator window when I click them.

I've been struggling with understanding query selectors and event listeners, so it's likely that I've made a mistake somewhere in my JavaScript code.

I've set up a query selector targeting the .window-content class and initialized the windowValue variable as an empty string. Additionally, I've implemented an Event Listener on the container housing the calculator to listen for clicks.

The problematic code snippet is displayed below:

const screen = document.querySelector(".window-content");
let windowValue = ""; 
document.querySelector(".container").addEventListener("click", function(e) {
  const tgt = e.target;
  if (tgt.tagName !== "button") return;

  let buttonText = tgt.innerText; 
    if (buttonText == 'X') { 
      buttonText = '*';
      windowValue += buttonText;
      screen.value = windowValue;
    } else if (buttonText == 'CA') { 
      windowValue = "";
      screen.value = windowValue;
    } else if (buttonText == '🡄') { 
      windowValue = windowValue.slice(0,-1);
      screen.value = windowValue;
    } else if (buttonText == '=') { 
      screen.value = operate(firstNum, secondNum, operator);
      windowValue = screen.value;
      firstNum = "";
      operator = "";
      secondNum = "";
    } else if (buttonText.match(/[0-9]/)) { 
      windowValue += buttonText; 
      screen.value = windowValue;
    } else { 
      firstNum = windowValue;
      operator = buttonText;
      windowValue = "";
      windowValue += buttonText;
    windowContent.innerText = windowValue;
    }
})

Answer â„–1

It seems like the issue lies in using querySelector; as it applies addEventListener only to the first element with the class .container, instead of all elements. Simply replace it with querySelectorAll and implement a loop to add the click event to all button elements.

const screen = document.querySelector(".window-content");
let windowValue = ""; 
[...document.querySelectorAll(".container")].forEach(function (container) {
  container.addEventListener("click", function(e) {
    const tgt = e.target;
    console.log(tgt);
    //if (tgt.tagName !== "button") return;

    let buttonText = tgt.innerText; 
    console.log(buttonText);
    if (buttonText == 'X') { 
      buttonText = '*';
      windowValue += buttonText;
      screen.value = windowValue;
    } else if (buttonText == 'CA') { 
      windowValue = "";
      screen.value = windowValue;
    } else if (buttonText == '🡄') { 
      windowValue = windowValue.slice(0,-1);
      screen.value = windowValue;
    } else if (buttonText == '=') { 
      screen.value = operate(firstNum, secondNum, operator);
      windowValue = screen.value;
      firstNum = "";
      operator = "";
      secondNum = "";
    } else if (buttonText.match(/[0-9]/)) { 
      windowValue += buttonText; 
      screen.value = windowValue;
    } else { 
      firstNum = windowValue;
      operator = buttonText;
      windowValue = "";
      windowValue += buttonText;
      windowContent.innerText = windowValue;
    }
  });
});
.btn {
  display: flex;
}

.container {
  display: inline-block;
}
<div class="btn">
  <button class="container">X</button>
  <button class="container">CA</button>
  <button class="container">🡄</button>
  <button class="container">=</button>
  <button class="container">1</button>
  <button class="container">2</button>
  <button class="container">3</button>
  <button class="container">4</button>
  <button class="container">5</button>
  <button class="container">6</button>
  <button class="container">7</button>
  <button class="container">8</button>
  <button class="container">9</button>
  <button class="container">0</button>
</div>
<br />
<textarea class="window-content"></textarea>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When adding another Mesh, an error occurs in three.js stating: "Uncaught TypeError: Cannot read property 'center' of undefined - three.js:6754."

As I delve into coding with JS, I decided to experiment with Three.js. Everything was running smoothly until I included the line scene.add(my_square);. From that point on, my code failed to work and displayed the following error: Uncaught TypeError: Canno ...

What could be the reason for the malfunction of the "includes" function in my JavaScript snake game

As a beginner in JavaScript, I've been learning CSS and HTML as well. I decided to practice my skills by creating a snake game without following any tutorials. I know my code might not be the best and lacks good practices, but I'm just doing this ...

Displaying time text in input element due to browser bug

I am faced with a perplexing puzzle that has left me scratching my head. Here are two seemingly identical pieces of javascript code, but one behaves unexpectedly (take note of the Console.Log): Updates the UI once, then abruptly stops updating: http://js ...

Is there a "Read more" link to expand the content on the page?

I am struggling to figure out why my JavaScript code for toggling between showing more text and less text is not functioning correctly. My goal is for the user to click on the "Show More" button to reveal additional text, and then be able to click on "Show ...

Preventing Bootstrap 4 slider images from shifting position when using background-attachment:fixed for a parallax effect

I'm trying to implement a Parallax scrolling effect on my Bootstrap 4 slider. However, every time the slider switches to the next image, the image needs to readjust itself into place. How can I avoid this? .customOverlayText { position: absolute; ...

Resolving DataTables Error

Here is my JavaScript code snippet. <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.2.1/css/but ...

What is the reason for having a filled array containing data on currency exchange rates within an asynchronous function, while simultaneously having an empty array located outside of it? - React

After struggling with this programming issue for the past 5 days, I'm reaching out for help. The challenge I'm facing involves retrieving the rate of a specific currency between 1 and 50000 from an API. While I have successfully managed to obtai ...

Encountering a theme issue in the makeStyles function within Material-UI version 5

While working on some React components, I created a styles.js file for each of them. I am following a YouTube tutorial that uses material-ui version 4, so I decided to upgrade to V5. Code snippet for the component (Form): import React from 'react&apo ...

experimenting with a TypeScript annotation

I have created a simple decorator that can trigger either stopPropagation() or preventDefault() based on certain conditions. I have thoroughly tested this decorator in my application and am confident that it works correctly. However, I encountered an issue ...

Executing a protractor test on Safari results in the message "Angular was not located on the webpage https://angularjs.org/"

Recently, I encountered an issue while trying to run a Protractor test on Safari, even when following the official example provided at http://www.protractortest.org/. Below are my conf.js and todo-spec.js files. The problem arises when I set browser.ignor ...

Why is it that the "await" keyword lacks the ability to truly await?

I created this code to access the google calendar API and retrieve information. To make it easier to understand, I added the variable x to the function. Initially, I expected x to be displayed as 1, however, it consistently shows up as 1. The main issue ...

Maintain your position on the current page when refreshing Angular 4

My Anuglar 4 application features multiple routes, with two main ones being Logging and List of items. Specifically, the routes are http://localhost:4200/#/ and http://localhost:4200/#/items. However, I've noticed that when I reload the page while on ...

Is it possible to turn off security features for a Heroku Postgres database?

My project doesn't involve sensitive data, so I'm not concerned about security vulnerabilities. I believe the issue lies in the connection between the App/server and the DB. I've searched on Youtube and Google for solutions, but the informa ...

Embedding a PDF file into an HTML form

For days, I have been on a relentless search for a solution to my problem to no avail. My ideal scenario involves embedding a fillable pdf form into an intranet html form for submission to the server, with the ability to parse field/values being a bonus b ...

The setTimeout function executes immediately without any delay

In my code, an html button triggers a jQuery function (let's call it funcOne) which then calls another function (funcTwo) recursively to modify CSS in the DOM. The funcTwo function involves setTimeout() calls to create a blinking effect by delaying th ...

Synchronizing client information in real-time: tips, tricks, and expert advice

Currently, I am developing a PHP backend and utilizing JS/Jquery for the front end of an application that aims to facilitate near real-time communication among users. My main concern right now is determining the most effective approach to achieve this goal ...

Troubleshooting Issue with Bootstrap 4 Modal Varying Content Display

Dealing with a minor issue where I'm unable to get a modal to fetch data from an HTML table and populate it into a Bootstrap 4 Modal. I've attempted various methods as evident in the code snippets below. Currently in a learning phase, I need to ...

Removing duplicates from a multidimensional array by comparing the first element in each subarray using Javascript

I need to obtain unique values from a multidimensional array. The uniqueness should be based on the first element of each item. let arr = [['item 1', 'item 2'],['item 1', 'item 5'],['item 3', 'item 4& ...

Tips for safeguarding the JSON data being transmitted from the AJAX file to jqGrid

I am incredibly grateful for the creation of jqGrid - it truly is a remarkable tool! My workflow involves sending JSON-encoded search criteria from my index.php file to grid.php, where it processes the data, queries the database, and sends back a JSON str ...

Load data from a file into a dropdown menu using node.js

Exploring the realm of front end development on my own has been quite a challenge. I am currently struggling with the concept of populating a drop down box with data from a file. While utilizing node and JavaScript, I have decided to stick to these techn ...