Wednesday 11 September 2013

create own support Ctrl+v, Ctrl+c, Ctrl+X and 'Numeric only' jquery plugin

(function ($) {
    $.fn.forceNumeric = function () {
        return this.each(function () {
            // bind handler of 'paste' event
            $(this).bind(
                {
                    paste: function (e) {
                        var content = e.originalEvent.clipboardData.getData('text/plain');
                        var regExp = /^\d+$/;
                        if (!regExp.test($.trim(content))) {
                            e.preventDefault();
                        }
                    }
                });
            $(this).keydown(function (e) {
                var key = e.which || e.keyCode;

                if (!e.shiftKey && !e.altKey) {
                    if ((key >= 48 && key <= 57 ||
                        // Numeric keypad
                        key >= 96 && key <= 105 ||
                        // comma, period and minus, . on keypad
                        key == 190 || key == 188 || key == 109 || key == 110 ||
                        // Backspace and Tab and Enter
                        key == 8 || key == 9 || key == 13 ||
                        // Home and End
                        key == 35 || key == 36 ||
                        // left and right arrows
                        key == 37 || key == 39 ||
                        // Del and Ins
                        key == 46 || key == 45) && !e.ctrlKey) {
                        return true;
                    }

                    // Allow: Ctrl+C, Ctrl+V, Ctrl+X
                    if ((e.keyCode == 67 || e.keyCode == 86 || e.keyCode == 88) &&
                        (e.ctrlKey === true || e.metaKey === true)) {
                        return true;
                    }
                }

                return e.preventDefault();
            });
        });
    };
}(jQuery));