Reputation: 601
I have built a sortable list using jQuery UI's sortable feature, this is working fine except that I need to be able to reorder the <li>
at the beginning depending upon a string containing the element's order but I cannot figure out the syntax how to do this with JavaScript.
Lets say I have the following:
<ul>
<li id="A" >Apple</li>
<li id="B" >Banana</li>
<li id="C" >Carrot</li>
</ul>
and the string "C,A,B"
I would like to have a JavaScript function for reordering my the items inside the which bases the ordering off of the order of the string. Ending up with this:
<ul>
<li id="C" >Carrot</li>
<li id="A" >Apple</li>
<li id="B" >Banana</li>
</ul>
I will be naturally splitting the string back out by its "," and ending up with an array of element Id's, but I am unsure of two main things in this.
1) What is the best way to get the element which the specified Id found in my split string array?
2) Once I have gotten that element and determined it is the correct element, what is the syntax for or best strategy for placing them in the proper order?
Upvotes: 2
Views: 944
Reputation: 490153
This should answer both (1) and (2).
You can split the string on the ,
delimiter to get an array, and then just loop through changing the order of the li
elements.
var order = 'C,A,B'.split(','),
ul = $('ul');
$.each(order, function(index, sort) {
$('#' + sort).appendTo(ul);
});
Upvotes: 5