Last Updated: September 09, 2019
·
9.246K
· albertovelandia

Order Select Options Alphabetically

IF you ever have to organize a Select alphabetically you can use this Little Snippet I assume you use jQuery but you can always apply the same logic to make it just Javascript

See it live here: https://tinker.io/37028/3

function orderSelect($element) {
    var options   = $element.find('option'),
        n_options = options.length,
        temp = [],
        parts,
        i;

    for(i = n_options; i --;) {
        temp[i] = options[i].text + "," + options[i].value ; 
    }

    temp.sort();

    for(i = n_options; i --;) {
        parts = temp[i].split(',');

        options[i].text  = parts[0];
        options[i].value = parts[1]; 
    }
}

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside