Reputation: 167
I have function that gets data from a database and displays it in the view:
function GetUsers() {
let url = "/Home/GetUsers";
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function(data) {
console.dir(data);
for (var i = 0; i < data.length; ++i) {
$('#taskresult3').append('<b>' + data[i].UserName + "-" + data[i].RoleName + "," + '</b>');
}
}
});
}
It displays it with comma, but after the last Username+RoleName
it adds a
comma too. As I understood I need to get last iteration of for loop? How I can fix this problem?
Upvotes: 4
Views: 4292
Reputation: 337560
You can avoid the comma and improve your logic by building the HTML in an array, then using join()
to display it, like this:
success: function(data) {
var html = data.map(function(item) {
return data[i].UserName + ' - ' + data[i].RoleName;
});
$('#taskresult3').append(html.join(',');
}
Also, keep in mind the semantic use of the <b>
tag:
However, you should not use
<b>
for styling text; instead, you should use the CSSfont-weight
property to create boldface text.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/b
I'd suggest placing the HTML you append within a container that has font-weight: bold
applied to it through CSS.
Upvotes: 1
Reputation: 40842
You could use map
and join
to solve this, instead of using a loop.
$('#taskresult3').append('<b>' + data.map(item => item.UserName + "-" + item.RoleName).join(',</b><b>') + '</b>')
map
would convert the array, to an array of item.UserName + "-" + item.RoleName
, this array then would be joined together using ,</b><b>
and the last part that is then missing is the first <b>
and the last </b>
Upvotes: 1
Reputation: 36703
Dont add comma for the last element.
for (var i = 0; i < data.length; ++i) {
if (i === data.length - 1)
$('#taskresult3').append('<b>' + data[i].UserName + "-" + data[i].RoleName '</b>');
else
$('#taskresult3').append('<b>' + data[i].UserName + "-" + data[i].RoleName + "," + '</b>');
}
There is one more approach using .join()
on arrays
var _html = [];
for (var i = 0; i < data.length; ++i) {
var _inhtml = '<b>' + data[i].UserName + "-" + data[i].RoleName+'</b>';
_html.push(_inhtml);
}
$('#taskresult3').append(_inhtml.join(","));
With this you can cut down the overhead of manipulating DOM multiple times.
Upvotes: 1
Reputation: 26961
I usually make a little trick for this cases:
var separator = "";
for (var i = 0; i < data.length; ++i) {
$('#taskresult3').append(separator + '<b>' + data[i].UserName + "-" + data[i].RoleName + '</b>');
separator = ",";
}
Upvotes: 11
Reputation: 92501
Simply check if the current element is the last element and if so, don't add the comma:
$('#taskresult3').append('<b>'+ data[i].UserName +"-"+ data[i].RoleName + (i === data.length - 1 ? "" : ",")+'</b>');
Upvotes: 7