What could be causing this addEventListener to fail when I am assigning elements to a class?

I've encountered an issue with my code where I have two text inputs and two date inputs. I tried to select all of them using QuerySelectorAll with a class, added a click listener that should change the textContent of a div element to "", but it's not working as expected.

Interestingly, when I try to run this logic by selecting one of the inputs with an ID, it works fine. However, it fails when I attempt to create a class that selects all four input elements. Can anyone point out what might be going wrong here?

    const getSum = () => {
  const inputs = ['dateInput1', 'dateInput2'];
  const outputs = ['result1', 'result2'];

  const arr = inputs.map(input => {
    return document.getElementById(input).value;
  });

  if(arr.every(element => !!element)){
    inputs.forEach((input, index) => {
    const inputValue = document.getElementById(input).value;
    if (inputValue.match(dateRegEx)) {
      var sum = 0;
      for (var i = 0; i < inputValue.length; i++) {
        const num = parseInt(inputValue.charAt(i));
        if (!isNaN(num)) {
          sum += num;
        }
      }
      const total = (sum - 1) % 9 + 1;
      document.getElementById(outputs[index]).textContent = "Your number is: " + total;
    } 
  });
  } else {
 document.getElementById("errorMsg").textContent = "*error* please enter two dates and two names";
   }
}

const sumButton = document.querySelector(".sumNumbers");
sumButton.addEventListener("click", getSum);

const dateRegEx = /^(19|20)\d{2}-(0\d{1}|1[0-2])-([0-2]\d{1}|3[0-1])$/;

function clearErrorMsg(){
  document.getElementById("errorMsg").textContent = "";
} 

const cLickDeletesError = document.querySelectorAll(".clickClear");
Array.from(clickDeletesError).forEach(function(cde){
 cde.addEventListener("click", clearErrorMsg);
}

const dateRegEx = /^(19|20)\d{2}-(0\d{1}|1[0-2])-([0-2]\d{1}|3[0-1])$/;

function clearErrorMsg(){
  document.getElementById("errorMsg").textContent = "";
} 

const cLickDeletesError = document.querySelectorAll(".clickClear");
Array.from(clickDeletesError).forEach(function(cde){
 cde.addEventListener("click", clearErrorMsg);
}

Answer №1

When using querySelectorAll, remember that it returns a collection and you cannot directly add an event listener to it. Instead, utilize the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax" rel="nofollow noreferrer">spread syntax</a> to convert it into an array. Then, use forEach to iterate through the elements and add the event listener.</p>

<p><div>
<div>
<pre class="lang-js"><code>function clearErrorMsg() {
  document.getElementById("errorMsg").textContent = "";
}
[...document.querySelectorAll(".clickClear")].forEach((e) => {
  e.addEventListener("click", clearErrorMsg)
});
<div class="cell-1" id="centerElement">
  <div id="cell-1-nest-l"></div>
  <div id="cell-2-nest-l"></div>
  <div id="cell-3-nest-l"></div>
  <div id="cell-4-nest-l"></div>
  <div id="cell-5-nest-l"></div>
  <div id="cell-6-nest-l">
    <input type="text" class="nameStyle1 clickClear" id="nameInput1" placeholder="Your Name"></div>

</div>

<div id='errorMsg'> Here is Error</div>

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

Issue with IE 11: Including card image inside anchor tags in Bootstrap 4 causes unwanted white space

I'm having an issue with my Bootstrap 4 card markup where the image is wrapped inside an anchor tag. The problem arises when viewing it in IE 11, as there is a large white space underneath the image, while everything displays fine in Chrome, Edge, and ...

jQuery: Revealing or concealing several divs upon selection alteration

When I populate a form, I want to display or hide multiple divs based on the OPTION selected in a DROPDOWN. Currently, my code works but the issue is that one div can be hidden or shown by multiple OPTIONS. As a result, these divs keep toggling between hi ...

What is the best way to incorporate intervals and polling in Angular 2 for seamless integration with Protractor?

I have an angular2 application that I am looking to test using protractor. Within this application, there is a page featuring a graph that updates at regular intervals with data generated on its own. It appears that one aspect of protractor is the abilit ...

Implementing dynamic styles for a checked mat-button-toggle in Angular 6

How can I customize my button-toggle when it is checked? The current code I have doesn't seem to be working... This is the code snippet: <mat-button-toggle-group #mytoggle (change)="selectoption($event)" value="{{num}}"> <mat-bu ...

Ensuring the text is positioned centrally and at the bottom of a table cell

Is there a way to center and align text at the bottom of a cell in table? This is my desired layout: ...

Error: Firebase is not recognized as a valid function

I have been attempting to go through the firebase Node tutorial at this URL: Running my node.js app leads to a crash with a "TypeError: Firebase is not a function" error. Here is an excerpt from my index.js file: var Firebase = require("firebase"); var f ...

Behold the magic of a three-column layout with sticky scroll behavior and an absolute

I am struggling with a layout that involves 3 columns, each with its own independent scroll. The first column contains an absolute element that should overflow on the x-axis, but I am having trouble getting the overflow-x:visible property to work when comb ...

When the onclick function is triggered, two or more characters will be displayed

Functionality: To input name and email, users must click on the virtual keyboard displayed on the screen. Characters entered will be shown in the input box. Implementation: The HTML keyboard interface and associated script have been developed successful ...

Transforming a Python list into a JavaScript array

Hey there, I'm in the process of creating a JavaScript array of dates to input into a jQuery datepicker addon. Here is my Django view: def autofill_featured(request): show_id = request.GET.get('show_id') show = Show.objects.get(id=s ...

I am trying to set up an AJAX call in my index.html to connect to a React endpoint, but instead of accessing the intended page, I am getting

I am attempting to execute an AJAX call in my static file index.html to a React endpoint, but instead of the desired response, I am seeing the React homepage. Here is the code snippet from my index.html: <div id="data"></div> <scr ...

Creating a customized SelectField component for Material-UI v1.0.0-alpha.21 with a fix for the Menu anchorEl problem

Currently, Material-UI v1.0.0 does not have a selectField implemented yet so I am attempting to create my own version using TextField, Menu, and MenuItem Components. Below is the code for my custom selectField: export default class SelectField extends Rea ...

Guide on creating a cookie verification process with no contents

Request for Assistance: let cartHelper = { cartCookieName: "_cart", getCart: function (callback = undefined) { return apiHelper.getRequest( "/carts", (response) => { documen ...

Always ensure that the horizontal scrollbar is visible without the need for vertical scrolling

I'm attempting to create a data grid-style layout where the left side is fixed and only the right side is scrollable. However, the entire div needs to be vertically scrollable. The concept is functioning correctly, but the horizontal scrollbar appears ...

The no-unused-expressions rule is triggered when an assignment or function call is expected

I'm just starting out in full stack development and I'm experimenting with coding to improve my understanding of frontend using React JS and Material UI. While working on this component, I encountered an error in the console at line 75 (this.prop ...

The functionality of the MVC jQuery grid is currently malfunctioning

Recently, I attempted to integrate a jQuery grid plugin from gijgo.com into my MVC application. Following the instructions provided on c-sharpcorner and/or codeproject meticulously, however, upon running the application, I encountered a troubling JavaScrip ...

Achieving different results by modifying an array within a forEach loop

I am currently working on a forEach() function that increments an array by one for each iteration. The problem I am facing is that whenever I try to display the value of the number variable in the browser's console, it only shows me the final state i ...

Achieving both vertical and horizontal center alignment specifically for mobile devices

Is there a way to center a column on mobile devices only while maintaining a fixed height for the section? <div class="" style="background-image: url(image url;); background-position: right bottom; background-size: cover; height: 462px;"> <div cl ...

Leveraging recompose utility within the structure

I am exploring the use of recompose utility functions as a React element, enabling me to incorporate them into JSX as higher-order components (HOC). const enhancedInput = props => { return (<OnlyUpdateForKeys keys={['name']> ...

immediate removal upon pressing the button

Struggling to remove data from a datatable when clicking the delete button for quick admin side action. My code isn't functioning properly, even after attempted fixes. Here's my code: <div class="table-responsive"> <table id="datas" cl ...

The problem of interpreting JSON using the JavaScript eval() function

Here is the JSON string provided : { "name":"Ruby on Rails Baseball Jersey", "price":"19.99", "id":"1025786064", "image":"" }, { "name":"Ruby on Rails Baseball Jersey", "price":"19.99", "id":"1025786064", "image":"" }, { "name ...