DroopyTersen
5/19/2015 - 7:53 PM

Automatically adds slashes

Automatically adds slashes

(function ($, window) {
    var defaults = {
        //not sure if we'll have defaults
    };
    var DroopyDatepicker = function (el, options) {
        this.$element = $(el);
        this.options = $.extend({}, defaults, options);
        this._defaults = defaults;
        this.init();
    };

    DroopyDatepicker.prototype.init = function () {
        var $input = (this.$element);
        $input.datepicker(this.options);
        //keypress processes numpad char codes better
        $input.on("keypress", this.handleKeydown.bind(this));
    };

    DroopyDatepicker.prototype.handleKeydown = function (e) {
        var self = this;
        //keypress fires before value actually change so skip an event loop tick
        setTimeout(function () {
            var value = self.$element.val();
            var numChars = value.length;
            var isDigit = (e.which >= 48 && e.which <= 57);

            //if value is 2 or 5 characters, and key is a digit, add slash
            if ((numChars === 2 || numChars === 5) && isDigit) {
                self.$element.val(value + "/");
            }
            // if 3 chars and no slash, insert the first slash
            else if (numChars === 3 && value.indexOf("/") < 0) {
                value = value[0] + value[1] + "/" + value[2];
                self.$element.val(value);
            }
            // if 6 chars and last char is not slash, insert the second slash
            else if (numChars === 6 && isDigit) {
                value = value.substr(0, 5) + "/" + value[5];
                self.$element.val(value);
            }

            return true;
        }, 1);

    };

    $.fn["droopyDatepicker"] = function (options) {
        return this.each(function () {
            new DroopyDatepicker(this, options);
        });
    };
})(jQuery, window);