esedic
3/4/2013 - 7:54 PM

multiSelectToCheckboxes.js

(function($) {

    var methods = {
        init: function() {
            var $ul = $("<ul/>").insertAfter(this);
            var baseId = "_" + $(this).attr("id");
            $(this).children("option").each(function(index) {
                var $option = $(this);
                var id = baseId + index;
                var $li = $("<li/>").appendTo($ul);
                var $checkbox = $("<input type='checkbox' id='" + id + "'/>").appendTo($li).change(function() {
                    if ($(this).is(":checked")) {
                        $option.attr("selected", "selected");
                    } else {
                        $option.removeAttr("selected");
                    }
                });
                if ($option.is(":selected")) {
                    $checkbox.attr("checked", "checked");
                }
                $checkbox.after("<label for='" + id + "'>" + $option.text() + "</label>");
            });
            $(this).hide();
        }
    };

    $.fn.multiSelectToCheckboxes = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.multiSelectToCheckboxes');
        }

    };

})(jQuery);