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\$

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.