I have a list. List should be indexed with id number, but how i can do
it? Should I get list id's to array and use sort or is there better
solutions for that?
<ul id='List'>
<li id="list_3">Apples</li>
<li id="list_1">Grapes</li>
<li id="list_2">Strawberries</li>
</ul>
<a href="#" onclick="sList()">Sortable</a>
<script>
function sList(){
</script>
I can't say this is the best way but something like this might get you
started:
<script type="text/javascript">
function sortList(id) {
var ul = document.getElementById(id);
var lis = new Array();
while (ul.getElementsByTagName('LI').length > 0) {
var li = ul.getElementsByTagName('LI')[0];
lis.push(li);
ul.removeChild(li);
}
lis.sort(function(a, b) {
if (a.id < b.id) {
return -1;
}
else if (a.id > b.id) {
return 1;
}
else {
return 0;
}
});
for (var i = 0; i < lis.length; i++) {
ul.appendChild(lis
);
}
}
</script>
...
<ul id="mylist">
<li id="item3">Item3</li>
<li id="item1">Item1</li>
<li id="item2">Item2</li>
</ul>
<input type="button" value="Sort" onclick="sortList('mylist');"/>
Basically just created an array of li elements and removed them from
the ul element, called the sort method on the array using a function
that compared ids, and put the li elements back in the ul element.
You could even allow them to sort in both orders (first up, then down)
via a simple change in the javascript:
<script type="text/javascript">
var reverse = new Array();
function sortList(id) {
var ul = document.getElementById(id);
var lis = new Array();
while (ul.getElementsByTagName('LI').length > 0) {
var li = ul.getElementsByTagName('LI')[0];
lis.push(li);
ul.removeChild(li);
}
lis.sort(function(a, b) {
if (a.id < b.id) {
return -1;
}
else if (a.id > b.id) {
return 1;
}
else {
return 0;
}
});
if (reverse[id] == true) {
lis.reverse();
}
reverse[id] = ! reverse[id];
for (var i = 0; i < lis.length; i++) {
ul.appendChild(lis);
}
}
</script>
HTH.