Reputation: 18123
I have created a list box like this, and created a title bar which helps to sort data:
ID Name
------------------------------------------------------------
ID1 Identity One
ID2 Identity Two
ID3 Identity Three
ID4 Identity Four
-------------------------------------------------------------
I have a requirement to sort above list based on ID and also on Name, means when user clicks ID, it should sort list based on ID and vice versa. But the problem is from data layer we are getting like this in a single line:
ID1  :Idenitity One
So we are printing the same in options tag, and getting output like above. Code to generate above output is:
<select id="selSort" size="10" style="width:350px" id="rpt">
<option value = "ID1">
ID1 Identity One
</option>
<option value = "ID2">
ID2 Identity Two
</option>
<option value = "ID4">
ID4 Identity Four
</option>
<option value = "ID3">
ID3 Identity Three
</option>
My question is how do I implement sorting facility for above scenario? Yes, I tried to sort, but it is sorting entire list box, not based on single value. At-least now what can I do is format incoming data such way that put all Ids in one array and names in another, so any guide/pointers on this appreciated. Please let me know if I haven't explained clearly
EDIT:
Code I tried to sort a list box
function sortSelect(selElem) {
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
tmpAry.sort();
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return;
}
Upvotes: 2
Views: 1044
Reputation: 4557
You can use the custom array sort take a look at this How to sort select base on an id ?
The idea here is just create a arrray and sort that based on its value and than dynamically create the option based on the sorted value.
Custom sorting code
source.sort(function (x, y) {
if (isAsc)
return y.id - x.id;
else
return x.id - y.id;
});
Upvotes: 3