1
\$\begingroup\$

I am trying to sort the options within a SELECT element. I wonder if I am doing it stupidly or not, so perhaps someone can look at it and provide suggestions.

// Function Name            = sortSelect(jsID, tagAttr)
// Function Purpose         = Sort elements within a select element by supplying the ID of the select element. Sorting parameter is based on the order of the tags passed in through tagAttr as an array with decreasing importance. CSS styles can be use as a sort parameters as well with syntax css:
// Example Call             = sortSelect("element", ["css: display", "id"]);

function sortSelect(jsID, tagAttr) {
    var jqID = "#"+jsID;
    var arrHold = [];
    var arrTemp = [];
    var arrObjs = [];
    var ct;
    var comp;

    if ($(jqID).prop("tagName").toUpperCase() == "SELECT") {
        $(jqID + " option").each(function() {
            arrHold = [];
            arrHold.push($(this));

            for (var j in tagAttr) {
                if (tagAttr[j].replace(/\s+/g, '').substring(0, 4) !== "css:") {
                    arrHold.push($(this).attr(tagAttr[j]));
                } else {
                    arrHold.push($(this).css(tagAttr[j].replace(/\s+/g, '').substring(4, tagAttr[j].length).trim()));
                }

                j+=1;
            }

            arrTemp.push(arrHold);
            ct+=1;
        });

        if (ct < $("#"+jsID).childElementCount) {
            var message = "Nodes other than 'option' has been detected, and may have been lost!"
            console.warn(message);
        }

        arrTemp = arrTemp.sort(function(a,b) {
            for (i=1; i<=tagAttr.length; i++) {
                comp = (''+a[i]).localeCompare(b[i]);

                if (comp != 0) {
                    return comp;
                }
            }

            return 0;
        }); 

        for (i=0; i < arrTemp.length; i++) {
            arrObjs.push(arrTemp[i][0]);
        }

        $(jqID).empty();
        $(jqID).append(arrObjs);
    }
}
\$\endgroup\$

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.