Jian Short
Jian Short

Reputation: 135

Jquery Add Line Breaks On html()

success: function(usernames){
           //alert(usernames); ["adam","adam","adam","adam","adam"]
           //alert(usernames.length); 36
           var participants_list= eval(usernames); //adam,adam,adam,adam,adam
           //alert(participants_list.length);5
           var username= '';
           for(var i=0; i<participants_list.length; i++){

               username += participants_list[i] + "\n";

           }
           $("#usernames").html(username);
       }
    });

I am trying to add line breaks to #usernames so that each adam will be displayed on a new line but I don't know how to do it. Thanks.

<td><div id="usernames">cindy</div></td>

Upvotes: 1

Views: 7154

Answers (2)

Pevara
Pevara

Reputation: 14308

Not to critisize you, but please allow me to improve your code a little:
- try avoiding the use of eval. eval is evil! In stead you should always try to return valid data by using jsonencode or serialize on the server side.
- in stead of building that for loop, it would be much easier to use the .each() function in jQuery

Your code would become something like this:

jQuery.each(usernames, function(index, value) {
  $('#usernames').append($('<tr><td>' + value + '</td></tr>'));   
});

I set up a small example for you here: http://jsfiddle.net/YsrWs/

Hope this helps!

Upvotes: 2

Hacknightly
Hacknightly

Reputation: 5164

You'll want to wrap each user name in a block level element to force them onto their own separate lines. For instance,

username = "<p>" + participants_list[i] + "</p>";

Perhaps even better in your case would be

username = "<tr class='user'><td>" + participants_list[i] + "</td></tr>";

$("your table id or class").append(username);

Upvotes: 3

Related Questions