Reputation: 1897
I'm trying to add this array to the DOM, with each string element as part of an unordered list. Below I try to set message[i] = the element of the array I want to append to the list, but it doesn't appear to be working. Fetch new is an callback function that gets an array of strings as it's input FYI. Basically I am trying to display each element in that array at the bottom of the ul. ul class="messages" fyi. Is there something wrong with the way I am assigning the variable value?
function fetchNew() {
var PrintChat = function (Chat_Messages) {
var y = Chat_Messages.length;
for (i = 0; i < y; i++) {
var message[i] = $('<li>Chat_Messages[i]<li>');
$('.messages').append(message[i]);
}
}
Upvotes: 0
Views: 113
Reputation: 28737
if fetchNew is a callback that gets an array of string, you're actually complicating it too much, a simpler method would be like so:
function fetchNew(myArray) { // receive the array as a parameter.
var length = myArray.length; // Cache the length of array
for (i = 0; i < length; i++) { // loop through the array.
var element = $('<li>' + myArray[i] + '<li>'); // concatenate the current value inside an LI and create a dom element.
$('.messages').append(element); // Add element to the parent container
}
}
Upvotes: 0
Reputation: 324620
I'm guessing it's literally outputting Chat_Messages[i]
repeatedly?
You kind of have to tell JavaScript that it's a variable to be concatenated. Try this:
$(".messages").append("<li>"+Chat_Messages[i]+"</li>");
Note that for safety reasons you should ensure that the message is properly escaped, or better yet use native DOM methods like createTextNode(Chat_Messages[i])
to protect your site from XSS attacks.
Upvotes: 1