Add sorting to js select.create() 01/1101/1
authorAlessandro Boch <aboch@cisco.com>
Wed, 4 Sep 2013 22:58:26 +0000 (15:58 -0700)
committerAlessandro Boch <aboch@cisco.com>
Wed, 4 Sep 2013 23:00:26 +0000 (16:00 -0700)
- Add optional parameter to the select constructor to get the options array sorted

Change-Id: Icb7d529ccbd4d343310f3c8397f59bc083f2cb52
Signed-off-by: Alessandro Boch <aboch@cisco.com>
opendaylight/web/root/src/main/resources/js/lib.js

index 90fd497..811d35e 100644 (file)
@@ -251,7 +251,7 @@ one.lib.modal = {
 one.lib.form = {
     // create select-option form element
     select : {
-        create : function(options, multiple) {
+        create : function(options, multiple, sort) {
             // assert - auto assign
             if (options == undefined)
                 options = {};
@@ -261,6 +261,24 @@ one.lib.form = {
                 $select.attr("multiple", "multiple");
             }
             var optionArray = one.lib.form.select.options(options);
+
+            // If specified, sort the option elements based on their text field
+            if (sort == true && optionArray.length > 1) {
+                var shifted = true;
+                var limit = optionArray.length;
+                while (shifted) {
+                    shifted = false;
+                    for ( var i = 1; i < limit; i++) {
+                        if (optionArray[i - 1].text() > optionArray[i].text()) {
+                            var swap = optionArray[i - 1];
+                            optionArray[i - 1] = optionArray[i];
+                            optionArray[i] = swap;
+                            shifted = true;
+                        }
+                    }
+                }
+            }
+
             $(optionArray).each(function(index, value) {
                 $select.append(value);
             });