Thursday, 20 June 2013

Add Select with Optgroup type in JEditable Plugin library

If you are new to JEditable Plugin Library, please read this introduction post and proceed furthur.

By default, JQuery JEditable Plugin library doesn't support select with optgroup field type. But it will support Text, Select, Textarea types. In order to make jEditable library supports select with optgroup field type. You need to make these following changes


Step1:

Add the below JS Code next to 'select' Option type in Jeditable library code (jquery.jeditable.js). This code will add a new option type 'optgroup'.
optgroup: {
    element: function (settings, original) {
        var select = $('<select />');
        $(this).append(select);
        return (select);
    },

    content: function (data, settings, original) {
        if (String == data.constructor) {
            eval('var json = ' + data);
        } else {
            var json = data;
        }

        var addto = $('select', this);
        $.each(json, function (i, optgroups) {
            $.each(optgroups, function (groupName, options) {
                var $optgroup = $("<optgroup>", {
                    label: groupName
                });

                $optgroup.appendTo(addto);

                $.each(options, function (j, option) {
                    var $option = $("<option>", {
                        text: option.name,
                        value: option.id
                    });

                    if (option.selected !== null && option.selected !== undefined && option.selected) {
                        $option.attr('selected', 'selected');
                    }
                    $option.appendTo($optgroup);
                });
            });
        });
    }
}

Step2:

In order to use the optgroup type inside your JEditable Code, you can have code something like this
$('.editable_optgroup').editable('yourfile.php', {
    type: 'optgroup',
    cancel: ' Cancel ',
    submit: ' Save ',
    onblur: 'ignore',
    indicator: 'Updating...',
    data: [{
        "Africa": [{
            "id": 1,
            "name": "Africa/Abidjan"
        }, {
            "id": 2,
            "name": "Africa/Accra"
        }]
    }, {
        "America": [{
            "id": 3,
            "name": "America/Adak"
        }, {
            "id": 4,
            "name": "America/Los_Angeles"
        }]
    }, {
        "Asia": [{
            "id": 5,
            "name": "Asia/Adan"
        }, {
            "id": 6,
            "name": "Asia/Kolkata"
        }]
    }]
});

Step3:

Following is the output in the browser



Hope, you enjoyed this Post.

No comments:

Post a Comment