Alex
Alex

Reputation: 7688

Finding li by data-order value and append content

How can I find the li's I need by the value of data-order?

The list is contained in:

var list = '
    <ul id="order_list"> <h3> Order: </h3>
       <li data-order="1"></li>
       <li data-order="2"></li>
       <li data-order="3"></li>
       <li data-order="4"></li>
       <li data-order="5"></li>
       <li data-order="6"></li>
     </ul>';

I have an object named data, which I retrieved with an ajax call. The order value is contained here and this is what I am trying to achieve

$.each(data, function(index, value) {
   // append data['title'] between <li ...> </li>
   // where data-order in <li> is data['order']
});

So I need to find li in var list filtered by data-order = data['order'] and append content from data;

My other post related to this: jquery append data to html according to order number

Upvotes: 0

Views: 596

Answers (1)

SeanCannon
SeanCannon

Reputation: 77966

EDIT: After seeing this post jquery append data to html according to order number


First, take the h3 out of your ul.

Second, make sure your list is in the DOM before you start using selectors to manipulate and append data.

Third, don't use line breaks in a string in JS like that. Use concatenation if you need multiple lines:

var list = '<h3> Order: </h3>' + 
    '<ul id="order_list">' + 
       '<li data-order="1">No featured news here, click to add</li>' + 
       '<li data-order="2">No featured news here, click to add</li>' + 
       '<li data-order="3">No featured news here, click to add</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>';

var data = [
    {
        id_news: 3,
        title: 'Alex...',
        category: 12,
        order: 1
    },
    {
        id_news: 12345,
        title: 'Obama...',
        category: 3,
        order: 3
    },
];

$(list).appendTo('body');

$.each(data, function(index, value) {
    $('#order_list li:eq(' + value['order'] + ')').html(value['title']);
});​

Demo: http://jsfiddle.net/aKcxW/

Upvotes: 1

Related Questions