Loop through an array of elements and dynamically attach event handlers using JavaScript

I'm currently utilizing a loop to generate an array of elements (links) and then connecting them with event handlers (one function for all) before adding them to the DOM. However, I've noticed that the event handler only reacts when I click on the very last link in the array. Here's the code snippet:

xGetUsers = new XMLHttpRequest();
xGetUsers.open("GET","dialogs.php",true);
xGetUsers.send();
xGetUsers.onreadystatechange = function(){
    if (xGetUsers.readyState==4 && xGetUsers.status==200){
        var jUsers=eval("("+xGetUsers.responseText+")");
        if(jUsers){
            var length = jUsers.length;
            var dialogLink = [];
            for(var i=0; i<length; i++) {
                dialogLink[i] = document.createElement("a");
                dialogLink[i].innerHTML = "Go dialog";
                dialogLink[i].usrn = jUsers[i][0];
                dialogLink[i].userID = parseInt(jUsers[i][3]);
                dialogLink[i].id = i;
                dialogLink[i].onclick = getDialog;
                var userinfo = '<div><p>'+jUsers[i][0];
                if(jUsers[i][1]!=0) userinfo += '('+jUsers[i][1]+')';
                userinfo += '</p><p>'+jUsers[i][2]+'</p></div>';
                main_div.innerHTML += userinfo;
                main_div.appendChild(dialogLink[i]);
                }
            }
        }
        
    }
}

The getDialog() function is as follows:

function getDialog(){
    enduser_id = this.userID;
    enduser_name = this.usrn;
    main_div.innerHTML = '<form><textarea  id="resz"></textarea><a href="" id="send_button" class="main-button">Send</a></form>';
    xLoadMessages.open("GET","get_messages.php?get_id="+enduser_id,true); 
    xLoadMessages.send();
    field = document.getElementById("resz");
    document.getElementById("send_button").onclick = function(){
        if(field.value!=""){
            var message="id="+enduser_id+"&message="+field.value;
            xSendMessage.open("POST","add_message.php",true);
            xSendMessage.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xSendMessage.send(message);
        }
        return false;
    }
    setTimeout(setRefresh, 3000);
    return false;
}

It appears that only the last link triggers the event. Despite my extensive search and experimentation with different ways to add event handlers, I haven't been able to resolve this issue. Any assistance would be greatly appreciated. Thank you.

Answer №1

It appears that the issue you are encountering stems from creating multiple elements with identical IDs and then using document.getElementById() to select them. As a result, only the last element with that ID will be recognized by your browser.

To address this problem more effectively, it is advisable to introduce modularity into your code. Separate functions should be implemented to handle Ajax requests, user interface development, and user interactions.

An uncomplicated implementation of an Ajax interface might resemble the following:

// Example implementation of an Ajax interface
function http() {
    // Functions for handling HTTP requests
}
// Other functions for handling GET and POST requests go here...

By employing the provided http.get() and http.post() helper functions, you can conveniently manage data and callbacks for your requests.

In addition to the above, a function that constructs HTML elements could prove beneficial for your user interface. An elementary version of such a function could be constructed as follows:

// Function for creating new HTML elements
function newElem(tagName, textContent) {
    // Implementation logic for creating and setting properties of HTML elements goes here...
}

You have now set the groundwork for generating user elements based on server responses. By adapting the example outlined in the previous code snippets, you can establish an interface free from global variables and HTML IDs, focusing instead on manipulation of DOM object references exclusively.

Despite the code's simplicity, it avoids reliance on global identifiers and favors interaction through DOM objects directly—an approach conducive to streamlined user interface creation without cluttering the global namespace.

Additional Insights:

  • Consider utilizing jQuery for enhanced functionality in managing HTTP requests, event handling, and dynamic element generation within your project.
  • Exploring HTML templating engines like Handlebars could significantly optimize the process of developing dynamic user interfaces with pre-defined templates.
  • For safe parsing of JSON data, favor the use of JSON.parse() over the potentially risky eval() method.
  • Exercise caution while implementing the presented code, ensuring a comprehensive understanding before integration. Verify its functionality and adapt it accordingly to suit your specific requirements.

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

Is there a way for me to generate a button that directs users to a variety of pages?

How can I create a button that takes me to a random page on my basic website when clicked? I'm having trouble changing the "href" attribute so that it links to a specific page. This is the JavaScript code I've come up with: document.addEventList ...

"Utilizing the include method in Rails 4 to serialize multiple variables within the to_json

When utilizing :include in json-response with to_json, I can achieve associations like this: def stats @orders = Order.all respond_to do |format| format.json { render :json => @orders.to_json(:include => :review) } end end Although it fun ...

Trying out the fetch api with Jest in a React Component: A step-by-step guide

As a newcomer to test driven development, I stumbled upon a section that talked about testing/mocking a fetch API. However, I am facing issues while trying to write my own test. In order to practice this concept, I created a simple weather app where I atte ...

The Ajax post is only activated on one occasion

Hello there, I am encountering a problem with an ajax function. My goal is to post data to a database and then update a table that displays the database information. Strangely, the process works fine the first time - data is posted and the table is refresh ...

Trouble with parseJSON when handling form POST in Python

I'm struggling with a javascript HTML page that has an action POST to a python file, expecting a JSON response back. Despite my efforts, I can't figure out how to catch and parse the JSON data. The HTML and python code excerpts below should show ...

Finding the row index in an Angular material table

How can I retrieve the row index in an Angular material table? <td mat-cell *matCellDef="let row"> <mat-checkbox (click)="$event.stopPropagation()&quo ...

Tips for structuring commands in Discord.js

I'm in the process of restructuring my bot's commands. I currently have a folder called commands with all my commands inside, but I want to make it more organized by categorizing them into moderators, fun, and global like this: commands > mo ...

"Utilize jQuery's append() method to reset content

I am looking for a way to reset after using the append() or before() function in jQuery. Can someone please assist me with this? Thank you so much in advance. if((#tag_id).text() == 'something'){ $(#tag_id).before("x"); } // I want to reset t ...

Guide to putting a new track at the start of a jPlayer playlist

I am currently working on a website that utilizes the jPlayer playlist feature. I am facing an issue, as I need to implement a function that adds a song to the beginning of the playlist, but the existing add function only appends songs to the end of the pl ...

Generating varying commitments from one function

I have encountered an issue where I am returning a promise from a function that is part of a $q.all array. Initially, this setup works perfectly on page load. However, the challenge arises when I need to call this function multiple times afterward to updat ...

Refresh Highchart Data with Formatted AJAX Response

I have implemented a Highcharts scatterplot on my webpage with the following structure: $(function() { $('#container').highcharts({ /*chart options, etc... this does not change*/ series: [/*there is some default data ...

What is the correct way to add parameters to a function expression in JavaScript?

function executeFunction(func) { func(); } var mathOperations = function(x, y) { var multiply = x * y; var add = x + y; var subtract = x - y; console.log("Addition: " + add); console.log("Subtraction: " + subtract); console.log("Multiplicati ...

The AJAX post request encountered a 404 error code

I'm attempting to make an AJAX post request from index.html in the root directory to my controller, but I keep receiving a 404 Not Found error in the Firefox console. index.html: <!DOCTYPE html> <html> <head> <title> ...

Using JQuery to animate elements by sliding them up, adding a delay, and then sliding them back down

Is there a way to implement sliding up the header with a delay and then sliding it back down repeatedly? Currently, I have a function bound to the form submission but the sliding action only occurs the first time. Here is the code snippet: $(document).rea ...

What is the best way to include an API key in the response to an Angular client application?

I'm working on transferring my API key from NodeJS to an Angular client application using $http, but I am unclear on the approach. Below is a snippet from my NodeJS file: // http://api.openweathermap.org/data/2.5/weather var express = require(' ...

The problem arises when using `$state.go` as it does not properly transfer the value to `$stateParams`

Within componentA, I am using an angular code: $state.go('home', {selectedFilter: "no_filter"}); In componentB, I have the following code: if ($stateParams.selectedFilter === 'no_filter') However, I am encountering an issue where $s ...

What is the best method for transmitting server errors to the client?

When using passport.js, I have all the required code in place. However, I am facing an issue with displaying errors on the client-side. Despite having the successRedirect set up correctly, nothing happens when a wrong password is entered, and no error mess ...

Pattern for handling errors in an efficient and streamlined manner

Currently, I am exploring the use of Express for developing a basic JSON API. However, I have concerns about how to effectively manage input parameter validation and error handling in my project. Errors can occur during both the validation process and when ...

The function Expo.Fingerprint.isEnrolledAsync will provide an output that includes information about fingerprint

Attempting to incorporate fingerprint authentication into my react native app. Utilized Expo SDK for this purpose. Although the Expo.Fingerprint.authenticateAsync() method claims to return a boolean, it actually returns an object when examined closely. E ...

Does the gltf loader in three.js have compatibility issues with Internet Explorer 11?

Despite the claims on the official website that gltf files should load in three.js scenes using IE11, I have been experiencing issues with the loader. Even the examples provided by three.js fail to work on Internet Explorer when it comes to loading gltf fi ...