Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jEditable select dropdowns change the order of the options

Here's the code I'm using to add a select dropdown to a table row using jEditable:

$('tr',this).find('td:eq(8)').css('cursor','pointer')
    .editable( 'update.php', {
        'type': "select",
        'loadurl': 'json.php',
        'onblur': 'submit',
        'callback': function( value, settings ) {
         // etc.
        }); 

The problem is that the options in the dropdown aren't sorted in the desired order. The original JSON coming from json.php is ordered by first name (as per client's request):

{"0":"Select driver...", "48":"Ashley Solis", "43":"Casey Segal", // etc. 

but in the final webpage, the options in the select dropdown are sorted by number.

It seems that jEditable is re-sorting the JSON data when I don't want it to. How do I fix this?

like image 428
Blazemonger Avatar asked Aug 20 '13 16:08

Blazemonger


3 Answers

A much easier workaround: Make the value non-numeric. Add a "_" at the beginning or something, and then strip it off when using the value after selection:

{"_0":"Select driver...", "_48":"Ashley Solis", "_43":"Casey Segal", // etc. 

That should preserve the order (at least in the browsers that I have tested).

like image 93
Pal Avatar answered Nov 09 '22 22:11

Pal


The Cause

The root of the problem isn't in jEditable, it's in the fact that the JSON that it's using to create the select dropdown is a single object. JavaScript treats object properties as unsorted. This is the key code in jEditable 1.7.1 (starting at line 492):

 /* 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;
 }
 for (var key in json) {
 // starts looping through the object properties

Normally, that for (var key in json) should loop through the JSON properties in the order that they're created. Instead, they're looped in numerical ("alphabetical") order.


The Fix

There are many ways to solve this, but the simplest is through an anonymously-authored jEditable plug-in I found on Pastebin through a Google search. Paste this into a new JavaScript file, and load it in your HTML file after jEditable:

<script src="/js/jquery.jeditable.min.js"></script>
<script src="/js/jquery.jeditable.plugins.js"></script>

In addition, the json.php file must be altered. Instead of returning JSON as an object, like this:

{"0":"Select driver...", "48":"Ashley Solis", "43":"Casey Segal", // etc. 

It should return JSON as a linear array that looks like this:

[" Select driver...||0","Ashley Solis||48","Casey Segal||43", // etc.

Note the use of whitespace at the start of the string "Select driver...", which ensures that it will be sorted to the first position. No other JavaScript needs to be changed, provided that json.php isn't being used anywhere else.


The Plugin

Here's the complete jEditable plugin I found on Pastebin:

// type: select (based on 1.7.1, added feature: sorted options)
$.editable.addInputType("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;
        }

        var aData = [];
        for (var key in json) {
            if (!json.hasOwnProperty(key)) {
                continue;
            }
            if ('selected' == key) {
                continue;
            }

            aData.push(json[key] + "||" + key);
        }

        // Sort
        aData.sort();

        // Create
        for (var key in aData) {
            var aDataSplit = aData[key].split("||");

            var option = $('<option />').val(aDataSplit[1]).append(aDataSplit[0]);
            $('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');
            }
        });
    }
});
like image 44
Blazemonger Avatar answered Nov 09 '22 23:11

Blazemonger


I had the same issue, ended up creating a custom input type called "server_ordered_select". To use it you need to do a few things:

  1. Change your server response to return an array of objects instead. Each object has only one key-value pair of id and label. For e.g.

    "[{'197':'Sterling'}, {'199':'US Dollar'}, {'185':'Canadian Dollar'}, {'200':'Yen'}]"
    
  2. Add the following somewhere before the jEditable init code:

    $.editable.addInputType('server_ordered_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;
            }
            var isArray = Object.prototype.toString.call(json) === '[object Array]',
                selected = "";
            for (var key in json) {
                var k, v;
                if (isArray) {
                    k = Object.keys(json[key])[0];
                    v = json[key][k];
                    if ('selected' == k) {
                        selected = v;
                        continue;
                    }
                } else {
                    if (!json.hasOwnProperty(key)) {
                        continue;
                    }
                    if ('selected' == key) {
                        selected = json['selected'];
                        continue;
                    }
                    k = key;
                    v = json[key];
                }
                var option = $('<option />').val(k).append(v);
                $('select', this).append(option);
            }
            /* Loop option again to set selected. IE needed this... */
            $('select', this).children().each(function() {
                if ($(this).val() == selected ||
                    $(this).text() == $.trim(original.revert)) {
                    $(this).attr('selected', 'selected');
                }
            });
        }
    });
    
  3. Now change the editable's type to 'server_ordered_select' in your editable init options.

    $('tr',this).find('td:eq(8)').css('cursor','pointer')
    .editable( 'update.php', {
        'type': "server_ordered_select",
        'loadurl': 'json.php',
        'onblur': 'submit',
        'callback': function( value, settings ) {
            // etc.
        });
    

The input type should also be compatible with the regular json responses for 'select' type, but then it won't keep the order from server.

like image 23
Dan7 Avatar answered Nov 09 '22 21:11

Dan7