I need to build a list with 6 li‘s and their values (empty or not) and then append it to an existing li.
Having these results in return from an sql query:
id_news title category order
------- -------- -------- -----
3 Alex... 12 1
12415 Obama... 3 3
With that data I need to build an in order by order list, and by that I mean that the list should be something like:
<ul>
<li data-order="1"> Alex... </li>
<li data-order="2"> No featured news here, click to add </li>
<li data-order="3"> Obama... </li>
<li data-order="4"> No featured news here, click to add </li>
<li data-order="5"> No featured news here, click to add </li>
<li data-order="6"> No featured news here, click to add </li>
</ul>
So, my questions are:
- Should I have a predefined list and add data there?
- Or, should I do it while building the list? If so, how?
The jQuery code that I have by now:
var sublist = '<ul id="order_list"> <h3> Order list: </h3>';
$.each(data, function(index, value) {
sublist += '<li data-target="'+value['id_news']+'">'+value['headline']+'</li>';
});
sublist += '</ul>';
list.append(sublist);
The important thing is to remember to just get all the markup string text the way you want it before inserting into the DOM, that’s going to be 99% of the optimization (not that you aren’t, just pointing out that that’s definitely the focus to keep).
As for accomplishing that: use the same code you have for creating the markup, but sort your “data” array first. Use javascript arrays’ “sort” function for that. This jsfiddle shows it happening.
I’m assuming that your data array holds objects with an order property that is numeric. Of course, if the property is named something else then change accordingly, and if it’s a string instead of numeric, then use Number() within the function in order for the math to work.