Skip to content
This repository was archived by the owner on Jul 29, 2022. It is now read-only.
This repository was archived by the owner on Jul 29, 2022. It is now read-only.

Fix: Sorting Select Dropdowns by Value #97

@jjwdesign

Description

@jjwdesign

Issue: Select Dropdowns created are sorted by key due to the sortless nature of javscript associative array (object).

It was annoying me that the data object was loosing the sorting order when passed into jEditable, so I modified that section of code (select content) to sort by the text value, rather than the key (option value). An option should probably be created to allow sorting by key or value (asc or desc).

        select: {
           element : function(settings, original) {
                var select = $('<select />');
                $(this).append(select);
                return(select);
            },
            content : function(data, settings, original) {
                /* If it is string assume it is json. */
                if (String == data.constructor) {      
                    eval ('var json = ' + data);
                } else {
                /* Otherwise assume it is a hash already. */
                    var json = data;
                }

                // Create tuples for Sorting
                var tuples = [];
                for (var key in json) {
                    tuples.push([key, json[key]]); // Store: [key, value]
                }
                tuples.sort(function(a, b) {
                    a = a[1];
                    b = b[1];
                    return a < b ? -1 : (a > b ? 1 : 0);
                });
                for (var i = 0; i < tuples.length; i++) {
                    var key = tuples[i][0];
                    var value = tuples[i][1];

                    if (!json.hasOwnProperty(key)) {
                        continue;
                    }
                    if ('selected' == key) {
                        continue;
                    } 
                    var option = $('<option />').val(key).append(json[key]);
                    $('select', this).append(option);    
                }                    
                /* Loop option again to set selected. IE needed this... */ 
                $('select', this).children().each(function() {
                    if ($(this).val() == json['selected'] || 
                        $(this).text() == $.trim(original.revert)) {
                            $(this).attr('selected', 'selected');
                    }
                });
            }
        }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions