0

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.
}
Community
  • 1
  • 1
user3354539
  • 1,245
  • 5
  • 21
  • 40
  • Is the select already built on page load, or are you building it as part of some javascript logic? – Taplar Nov 29 '16 at 03:19
  • Works fine for me -> https://jsfiddle.net/7hr7st8r/ but that's not really how you want to sort a list, you should move the elements rather than resetting the value and text of each option – adeneo Nov 29 '16 at 03:24
  • Taplar, In the on page load function, I have `$("#id_language_code").change(sortCountryNames);` and I also have in the on page load `sortCountryNames()` – user3354539 Nov 29 '16 at 03:24
  • adeneo, do you have an example of your suggestion? I would like to try your solution. – user3354539 Nov 29 '16 at 03:27
  • 1
    Like this -> https://jsfiddle.net/jtmnso19/1/ – adeneo Nov 29 '16 at 03:28
  • ^ that includes a `trigger` call that executes the function on pageload as well – adeneo Nov 29 '16 at 03:28
  • @user3354539 that tells me where you are binding and when you are calling that method. that does not answer my question about if the select is prebuilt on page load or created dynamically before any sorting happens. – Taplar Nov 29 '16 at 03:57

0 Answers0