I am a newbie, but by reading this this post, I have been able to create a js function to sort a select list of multi language country names by the users language.
The OP of post seems to have a similar scenario to me.
When I change the select list, the function to sort the country names in the new language is called and works.
However, I am unsure how to make the select list sort when the page first loads. I have tried placing a call to the function in the $(document).ready(function() {
, but this does not sort the list when the page is loaded. There may be a simple solution, but I cannot see it.
Does anyone have any suggestions?
Here is my working function:
function sortCountryNames() {
// sort the country names in alphabetical order.
var selected = $("#country_names").val(); // preserve the users selected value.
var options = $('#country_names option');
var arr = options.map(function(_, o) {
return {t: $(o).text(), v: o.value};
}).get();
arr.sort(function(o1, o2) {
return o1.t.toLowerCase().localeCompare(o2.t.toLowerCase());
});
options.each(function(i, o) {
o.value = arr[i].v;
$(o).text(arr[i].t);
});
$("#country_names").val(selected); // assign the preserved users selected value.
}