Using jQuery to Dynamically Insert Into List Alphabetically

Posted by Dex on Stack Overflow See other posts from Stack Overflow or by Dex
Published on 2010-05-22T02:37:20Z Indexed on 2010/05/22 2:40 UTC
Read the original article Hit count: 376

Filed under:
|
|

I have two ordered lists next to each other.

When I take a node out of one list I want to insert it alphabetically into the other list. The catch is that I want to take just the one element out and place it back in the other list without refreshing the entire list.

The strange thing is that when I insert into the list on the right, it works fine, but when I insert back into the list on the left, the order never comes out right.

I have also tried reading everything into an array and sorting it there just in case the children() method isn't returning things in the order they are displayed, but I still get the same results.

Here is my jQuery:

function moveNode(node, to_list, order_by){

    rightful_index = 1;
    $(to_list)
        .children()
        .each(function(){
            var ordering_field = (order_by == "A") ? "ingredient_display" : "local_counter";

            var compA = $(node).attr(ordering_field).toUpperCase();
            var compB = $(this).attr(ordering_field).toUpperCase();
            var C = ((compA > compB) ? 1 : 0);
            if( C == 1 ){
                rightful_index++;
            }
        });

    if(rightful_index > $(to_list).children().length){
        $(node).fadeOut("fast", function(){
            $(to_list).append($(node));
            $(node).fadeIn("fast");
        }); 
    }else{
        $(node).fadeOut("fast", function(){
            $(to_list + " li:nth-child(" + rightful_index + ")").before($(node));
            $(node).fadeIn("fast");
        });
    }

}

Here is what my html looks like:

<ol>
<li ingredient_display="Enriched Pasta" ingredient_id="101635" local_counter="1">
     <span class="rank">1</span>
     <span class="rounded-corners">
          <span class="plus_sign">&nbsp;&nbsp;+&nbsp;&nbsp;</span>
          <div class="ingredient">Enriched Pasta</div> 
          <span class="minus_sign">&nbsp;&nbsp;-&nbsp;&nbsp;</span>
     </span>
</li>
</ol>

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about dynamic