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.