Reputation: 311
I'm making a chat application in js/java. It has a list of online users off to the side, and I wanted the users' names to be clickable so that if you click them, you can send that person a private message. Everything is working and I tested the code below to make sure that clicking a user's name triggers the function (button()).
What I need it to do: in the function updateChat(), line id("userlist"), it needs to be able to pass the text from the list item that was clicked on to the function button(). I need to set that username as a variable so that the next time that user sends a message, its sent to that one user and not broadcasted.
It won't let me pass "user" as an argument and I'm not sure how to pass that text along. Thank you
var privmsg = "";
function updateChat(msg) { // Update chat-panel and list of connected users
let data = JSON.parse(msg.data);
id("chat").insertAdjacentHTML("afterbegin", data.userMessage);
id("userlist").innerHTML = data.userlist.map(user => "<li role=\"presentation\"
class=\"link\" value=\"thing\" onclick=\"button(user)\"><span>" + user + "</span>
</li>").join("");
}
function button(newuser){
String(newuser);
privmsg = newuser;
}
Upvotes: 0
Views: 427
Reputation: 10148
You just need concat the user
as string
argument to the called function like
button('" + user + "')
Here is example snippet
var users = ["A", "B", "C"];
document.getElementById("userlist").innerHTML = users.map(function (user) {
return "<li role=\"presentation\" \n class=\"link\" value=\"thing\" onclick=\"button('" + user + "')\"><span>\" + " + user + " + \"</span</li>";
});
function button(newuser){
alert(newuser)
privmsg = newuser;
}
<ul id="userlist"></ul>
Upvotes: 1