What is the correct way to create a click event for retrieved "buttons"?

I am retrieving all users from the database using this code snippet

fetch("/api/v1/users", {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json'
      }
})
.then(function(res) {
    return res.json();
})
.then(function(json) {
    json.data.forEach((elem) => {
        Object.values(elem).forEach((item) => {
            if(item != "" && typeof item == "string") {
                document.querySelector('.users__list').appendChild(users.createElement('div', 'users__user-field', '', `<p>${item}</p>`))
            }
        })
    })
})

Once the users are fetched, I create an element and append it to the list. This process works without any issues, but there's a problem!

The following section of code is causing an issue

const selectableUsers = {
    users: document.querySelectorAll('.users__user-field'),
    click(elem) {
        this.reset()
        elem.classList.toggle('selected')
    },
    reset() {
        this.users.forEach((elem) => {
            elem.classList.remove('selected')
        })
    }
}

window.onload = () => {
    document.querySelectorAll('.users__user-field').forEach((elem) => {elem.addEventListener('click', () => {selectableUsers.click(elem)})})
}

In my algorithm, after generating elements and loading the window, all items with the class users__user-field should have a click event to toggle the selected class. However, this functionality doesn't seem to be working as intended. I'm not sure why. Can you assist me?

Answer №1

One common mistake is assuming that users are fetched and added as DOM elements when the window is loaded, but this is not true. You should set the select behavior after fetching the users list in order to avoid trying to add a select event to an empty list of DOM elements.


fetch("/api/v1/users", {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json'
      }
})
.then(function(res) {
    return res.json();
})
.then(function(json) {
    json.data.forEach((elem) => {
        Object.values(elem).forEach((item) => {
            if(item != "" && typeof item == "string") {
                document.querySelector('.users__list').appendChild(users.createElement('div', 'users__user-field', '', `<p>${item}</p>`))
// -------------->
                document.querySelectorAll('.users__user-field').forEach((elem) => {elem.addEventListener('click', () => {selectableUsers.click(elem)})})            
// -------------->
             }
        })
    })
})

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

Maintaining a date attribute for scheduling events

I am seeking advice on a current issue I am facing. Currently, I have a calendar that displays events through one route "/events" in a monthly format. Users can navigate between months by clicking <<< or >>> buttons and view event details ...

The use of script src with vue.js is causing issues

I am looking to move my Vue code into an external .js file. Since I am new to Vue, I am trying to keep it simple without using webpack. However, I have encountered an issue where Vue does not work when using the script src tag in the html file. For instanc ...

Discovering the wonders of React and Javascript through the powerful Map function

I've exhausted all my knowledge of map functions and syntax, but I keep encountering the error TypeError: Cannot read property 'action' of undefined. This issue seems to stem from this line: constructor(data=[]). Typically, I am only familia ...

Having difficulties redirecting with the button's onclick function

I'm struggling to redirect users to another page using a button (assuming the hostname is localhost:8000) $('#getFruit').attr('onclick', window.location.host + '/getFruit/banana') <script src="https://cdnjs.cloudfl ...

Dynamically Growing Navigation Bar Elements with Nested Subcategories Based on Class Identification

Let's say you have a menu bar structured as follows: <nav> <ul class="nav"> <li class="menu1"><a href="#">Menu Item 1</a></li> <li class="menu2"><a href="#">Menu Item 2</a> <ul& ...

Various activities tailored to the amount of clicks

I've encountered some difficulties trying to achieve a specific functionality: https://jsfiddle.net/CreativeAU/ys12ed05/ warningbutton.onclick = function buttonClicks() { count += 1; if (count > 1) { window.location.href = "http://www.google.com. ...

Could someone please guide me on how to use JQuery to set a radio button as checked?

<input type="radio" name="sort" value="2" id="myradio"> Is there a way to set this as the selected option using JQUERY? ...

Calling a JavaScript function using string parameters

Lately, I've stumbled upon an issue when attempting to execute a function with multiple arguments. <button type = "button" id = "clickmepls" onclick = killButton("clickmepls", "grave1")> Click me please </button> The definition of the fu ...

Problem with assigning onclick to a function

I've been working on adding an onclick function to my code, using the following line: newbutton.onclick = whoWon(this.id) Here's some other relevant code: var winner; function whoWon(name){ winner = name; } The issue I'm facing is tha ...

Clicking on a column or x-axis category in Highcharts will automatically include the job number in the page URL

Check out the code I've put together: http://jsfiddle.net/a9QwS/ I'm looking to add functionality where clicking on a column or x-axis label will append its data to the URL. For example, in PHP, I can do something like this: echo " <td sty ...

Socket.io: sending signals without receiving any responses

I've been working on a real-time socket.io project that involves a collaborative whiteboard app. I'm facing some issues with emitting data. server.js const express = require('express') const app = express(); const http = require(&apos ...

Looking to test form submissions in React using Jest and Enzyme? Keep running into the error "Cannot read property 'preventDefault' of undefined"?

Currently, I am developing a test to validate whether the error Notification component is displayed when the login form is submitted without any data. describe('User signin', () => { it('should fail if no credentials are provided&apos ...

Displaying PHP content using JavaScript classes

I have a popup feature implemented in JavaScript and all the necessary scripts added to my HTML page. I am attempting to load a PHP page in the popup when the submit button of my form is clicked. The popup is functioning correctly for buttons like the one ...

Using ASP.NET MVC and jQuery Ajax to close and refresh a parent table from a modal dialog

I am relatively new to both MVC and jQuery, and I'm struggling to make them work together. I've managed to put together a modal dialog form with an ajax postback, but the UI is presenting challenges for me. Despite looking for examples of MVC and ...

Issues with dynamically loading jQuery arise specifically on certain websites

Code: initializeJQuery(); function initializeJQuery() { if (typeof jQuery === "undefined") { var scriptElement = document.createElement('script'); scriptElement.setAttribute("type", "text/javascript"); scriptElement.setAttribute("sr ...

"Revolutionary jQuery plugin designed to function independently of HTML elements

Is it possible to create a jQuery plugin that can be executed without the use of an element selector? Typically, we use: $('#myElementID').myPluginFunction(myVariables); But, is there a way to do it like this instead? $.myPluginFunction(my ...

Converting JSON to JS in Django results in an error: SyntaxError indicating a missing colon after the property

I'm trying to figure out how to incorporate a JSON file into a script. I've been unsuccessful in loading it from the filesystem, so I created a view that serves the JSON data directly to the page like this: def graph(request, d): ...

Enhancing input value by incorporating selected options from multiple choices

I am working with 2 select boxes. <select id="field1" class="inputtextbox required" size="0"> <option value="Student">Student</option> <option value="Teacher">Teacher</option> <option value="Director">Director</optio ...

Struggling to retrieve the data from my table (getElementById function is malfunctioning)

I am attempting to retrieve a line from a dynamic table once the "reserve" button is clicked (or the line itself is clicked if that is important), but the 'getElementById' function is not returning anything (I want to display them in an input). H ...

Click event inside a repeat loop

Working with AngularJS, I have a collection of colors that each have a specific title and type. These colors are displayed in a list format on the webpage. Now, I am looking to enhance this by incorporating a menu option that allows users to filter and vi ...