hiero
hiero

Reputation: 220

Change html position with jQuery

I'm trying to change the position of some list with jQuery in function of an array

http://jsfiddle.net/6r5jp5Lk/9/

$('div').each(function() {
   var answer = JSON.parse('[' + $(this).find('.order').val() + ']'),
   list = $(this).find('ul');                     

   $.each(answer, function(index, value) {
      list.append($('li[data-order="' + value + '"]'));
   });

});

Why the content is appending twice?

Upvotes: 0

Views: 55

Answers (3)

Saurabh Sharma
Saurabh Sharma

Reputation: 4894

You are not closing your div tags, if you check you have 4 div tags. Check the updated jsfiddle.

<div>
<ul class="list">
    <li data-order="1">1</li>
    <li data-order="2">2</li>
    <li data-order="3">3</li>
    <li data-order="4">4</li>
    <input class="order" type="hidden" value="4,2,1,3" />
</ul>
</div>
    
<div>
<ul class="list">
    <li data-order="1">1</li>
    <li data-order="2">2</li>
    <li data-order="3">3</li>
    <li data-order="4">4</li>
    <input class="order" type="hidden" value="3,2,4,1" />
</ul>
</div>

 

http://jsfiddle.net/6r5jp5Lk/16/

Upvotes: 1

hiero
hiero

Reputation: 220

I fixed http://jsfiddle.net/6r5jp5Lk/15/

$('.list').each(function() {
   var answer = $(this).find('.order').val().split(','),
   list = $(this);

   $.each(answer, function(index, value) {
      list.append($('li[data-order="' + value + '"]', list));
   });

});

Upvotes: 0

Alex J
Alex J

Reputation: 1019

Change your div to .list and it works fine

$('.list').each(function() {
   var answer = JSON.parse('[' + $(this).find('.order').val() + ']'),
       list = $(this).find('ul');                     

       $.each(answer, function(index, value) {
          list.append($('li[data-order="' + value + '"]'));
       });

});

Upvotes: 3

Related Questions