1
\$\begingroup\$

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) {
            $(evt.target).on("input",
                function (evt2) {
                    evt2.target.value = evt2.target.value.replace(/\D+/g, "");
                    $(evt2.target).off("input");
                }
            );
        }
    );
}
\$\endgroup\$
1
  • 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, 2019 at 20:08

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.