Reputation: 3071
I am returning JSON to display a history of comments starting with the most recent.
I'm trying to set a number to a class in a list item tag.
For example, I'm trying to achieve this:
<li class="1">comments</li>
<li class="2">comments</li>
<li class="3">comments</li>
// and so on
I am using the following:
$.post('process/searchComments.php', {histuid: histuid}, function(data)
{
var obj = JSON.parse(data);
$('#transactionHistory').empty();
var htmlToInsert = obj.map(function (item)
{
var number = 0;
number++;
return '<li class="'+number+'">item.comment</li>';
}).join('');
$('#transactionHistory').html(htmlToInsert);
});
But I'm returning this:
<li class="1">comments</li>
<li class="1">comments</li>
<li class="1">comments</li>
// and so on
How can I alter my code so that it shows the consecutive numbers in the classes?
Upvotes: 1
Views: 40
Reputation: 3
It´s happening because you define number and set it to 0 in every iteration. Try it:
var number = 0;
$.post('process/searchComments.php', {histuid: histuid}, function(data)
{
var obj = JSON.parse(data);
$('#transactionHistory').empty();
var htmlToInsert = obj.map(function (item)
{
number++;
return '<li class="'+number+'">item.comment</li>';
}).join('');
$('#transactionHistory').html(htmlToInsert);
});
Upvotes: 0
Reputation: 337580
Your problem is because you define number
and set it to 0
in every iteration.
To fix the problem you can use the second argument of the map()
handler function, which is the index of the current element within the set you're iterating through. You can concatenate that to your string instead:
var data = '["lorem","ipsum","dolor","sit"]';
var obj = JSON.parse(data);
var htmlToInsert = obj.map(function(value, i) {
return '<li class="' + (i + 1) + '">item.comment</li>';
});
$('#transactionHistory').html(htmlToInsert);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="transactionHistory"></ul>
Note that you don't need to call empty()
as html()
overwrites the values in the element anyway.
I have been asked to highlight the most recent comment. I figured I could just set the class using JQuery, then use CSS to highlight the class with 1. The comments are returned with the most recent being the first
In this case you can just append the HTML and use CSS to select the first one. This way you don't need to worry about any extraneous classes on the content you append:
var data = '["lorem","ipsum","dolor","sit"]';
var obj = JSON.parse(data);
var htmlToInsert = obj.map(v => `<li>${v}</li>`);
$('#transactionHistory').html(htmlToInsert);
ul li:first-child {
color: #C00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="transactionHistory"></ul>
Upvotes: 1