enkdr
enkdr

Reputation: 363

Re order list items jquery

Without using scrollable - I am trying to use a 'click' to move (nested) ul's up or down. However in this example: console.log = [] ? I know its ugly and Im probably not going to use it but I was more interested in why I cant get and result for 'prevList'?

$(function(){
$('.moveUp').click(function(){
    theList = $(this).parent().parent();        
    prevList = $(this).parent().parent().prev();
    console.log(prevList);              
        });
});



<ul>
<li>

<div class="category-list">
<ul>
<li>Category: other</li>
<li>Edit this Category</li>
<li>Delete this Category</li>
<li class="moveUp">Move up</li>
<li class="moveDown">Move down</li>
</ul>
</div>

<div class="category-list">
<ul>
<li>Category: other</li>
<li>Edit this Category</li>
<li>Delete this Category</li>
<li class="moveUp">Move up</li>
<li class="moveDown">Move down</li>
</ul>
</div>

<div class="category-list">
<ul>
<li>Category: other</li>
<li>Edit this Category</li>
<li>Delete this Category</li>
<li class="moveUp">Move up</li>
<li class="moveDown">Move down</li>
</ul>
</div>

</li>

<li>Some other List Item</li>

<li>Ditto</li>

</ul>

Upvotes: 0

Views: 442

Answers (2)

Sparkup
Sparkup

Reputation: 3754

This works if you give .category-list divs and uls an id

$('.moveUp').click(function(){

    var theList = $(this).parent(); 
    var theListparentId = $(this).parent().parent().attr('id');     
    var prevList = $(this).parent().parent().prev().children();
    var prevListparentId = $(this).parent().parent().prev().attr('id');

    if(prevListparentId !== undefined){

        $('#'+prevListparentId).html(theList);
        $('#'+theListparentId).html(prevList);

      } else {

        alert('No previous');

      }              
    });

$('.moveDown').click(function(){

    var theList = $(this).parent(); 
    var theListparentId = $(this).parent().parent().attr('id');        
    var nextList = $(this).parent().parent().next().children();
    var nextListparentId =$(this).parent().parent().next().attr('id');

    if(nextListparentId !== undefined){

        $('#'+nextListparentId).html(theList);
        $('#'+theListparentId).html(nextList); 

     } else {

        alert('No next');

     }
   });
});

As Kingjiv noted your not getting a result for 'prevList' if there isn't one i.e prevListparentId !== undefined

Upvotes: 0

James Montagne
James Montagne

Reputation: 78650

The upper list has no prev. The other lists seem to work fine and the console shows that it gets the previous div. prev does not wrap around, so if the element is the first child then it does not get anything.

Upvotes: 1

Related Questions