I have an unordered (dynamic generated via jsp <c:out>
-tags) list of options in a <select>
-tag.
After the tag has been rendered, I reorder it with a simple JavaScript function.
If I use the onClick
- event handler of the <select>
-element, I'll get / see the ordered list on the webpage. If I append the function to my onLoaded
-event handler, the function will be called and the debugger shows me the correct values, but the resulting order of my option
-elements is not sorted.
If i add the method call after the dom-element with a plain <script>
-tag, the same behavior happens.
Limitations
- No jQuery
- Data source is not sortable
onClick
-handler is not a prober solution- Has to work in old browsers
JavaScript Source
function sortSelectById(elementId) {
var list = document.getElementById(elementId);
var options = []
for(var i = 0; i < list.length; i++) {
options[i] = [];
options[i][0] = list.options[i].text;
options[i][1] = list.options[i].value;
options[i][2] = list.options[i].selected;
}
options.sort();
for (var i = 0; i < options.length; i++) {
list.options[i].text = options[i][0];
list.options[i].value = options[i][1];
list.options[i].selected = options[i][2];
}
return;
}