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>
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>
Share
Improve this question
edited Aug 21, 2012 at 18:01
Jian Short
asked Aug 21, 2012 at 17:54
Jian ShortJian Short
1351 gold badge2 silver badges13 bronze badges
4
-
5
You can either use
<br/>
generally a bad practice or modify the HTML structure in a way that makes sense:<ul id="usernames"><li>cindy</li><li>adam</li></ul>
You can then use CSS to change how this would be displayed. – Shmiddty Commented Aug 21, 2012 at 17:58 - Would it be a better way if I can somehow create a new tr/td with each "adam"? You got some pointers? – Jian Short Commented Aug 21, 2012 at 18:03
- 2 You should generally be avoiding tables like Jersey Shore. – Winfield Trail Commented Aug 21, 2012 at 18:06
-
2
That would depend on the purpose of this display. Generally speaking, tables should be used only for tabular data. So yes, it could be appropriate to generate a new row for each User. If you're just listing the users, it is better to use a list.
<ul> or <ol>
– Shmiddty Commented Aug 21, 2012 at 18:08
2 Answers
Reset to default 3You'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);
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 bee 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/YsrWs/
Hope this helps!