I wrote this small jQuery plugin to set some fields so that they allow only 0-9 digits to be entered.

I intended to do that by preventing user from typing, pasting or dropping non-digit content.

It seems to work (on Firefox), but I'd like to know if this code has some issue or unpredicted effect I'm not seeing now.

$.fn.onlyDigits = function () {
    return this.val("").off("keypress").on("keypress",
        function (evt) {
            evt = evt || window.evt;
            return /\d/.test("" + evt.originalEvent.key);
    ).off("drop paste").on("drop paste",
        function (evt) {
                function (evt2) {
                    evt2.target.value = evt2.target.value.replace(/\D+/g, "");
  • 1
    \$\begingroup\$ Very nice and for me educational. A side effect that could be a problem in some scenario's is that it is not possible to input a decimal point. \$\endgroup\$ – Hans Dash Feb 18 '19 at 20:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.