On a JSP page I have a following declaration:
<html:select property="filterBookingTargetId" styleClass="input_middle" >
<html:option value="0">-all-</html:option>
<html:options collection="bookTargetTypes" property="key" labelProperty="value"/>
</html:select>
where collection bookTargetTypes
is a set of key-value (int, String) pairs implemented in Java as a HashMap and read by a server.
If I could use jQuery, I would implement it similarly to answers present on the Stack discussion here. Unfortunately, I can't; nor can I sort those values before they are uploaded to the server i. e. in Java, on the code level.
The underlying question is, how in pure JavaScript can I refer to bookTargetTypes
collection to sort them alphabetically before they are shown on the page?
Example values of "bookTargetTypes
" collection, after they are rendered on the page, are shown below:
<html:option value="5">bbb</html:option>
<html:option value="13">ccC</html:option>
<html:option value="1">Aaa</html:option>
[UPDATE]
<script language="javascript">
function sortOptions() {
var options = document.getElementById('myselect').options;
var optionsArray = [];
for (var i = 0; i < options.length; i++) {
optionsArray.push(options[i]);
}
optionsArray = optionsArray.sort(function (a, b) {
return a.innerHTML.toLowerCase().charCodeAt(0) - b.innerHTML.toLowerCase().charCodeAt(0);
});
for (var i = 0; i <= options.length; i++) {
options[i] = optionsArray[i];
}
options[0].selected = true;
}
sortOptions();
</script>
<input type="hidden" name="method" value="listSettlementFiles">
<input type="hidden" name="pageNo" value="">
<input type="hidden" name="countPerPage" value="">
<input type="hidden" name="sc" value="">
<div class="search_bar" id="search" name="search_div">
<table align="center" width="100%">
<tr>
<td align="center">
<LABEL>Name of channels</LABEL>
<select name="filterBookingTargetId" id="myselect" class="input_middle">
<option value="17">Baa</option>
<option value="15">Paa</option>
<option value="2">Saaa</option>
<option value="9">Daaa</option>
<option value="6">Naaa</option>
<option value="1">Eaaa</option>
<option value="14">Sdda</option>
<option value="7">Raaa</option>
<option value="22">Pdddaa</option>
</select>