Skip to content

Instantly share code, notes, and snippets.

@DroopyTersen
Created May 19, 2015 19:53
Show Gist options
  • Save DroopyTersen/e821cef12ac4d3564ac9 to your computer and use it in GitHub Desktop.
Save DroopyTersen/e821cef12ac4d3564ac9 to your computer and use it in GitHub Desktop.
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment