Best way to restrict a text field to numbers only?

前端 未结 29 1690
长情又很酷
长情又很酷 2020-12-04 22:01

I\'m using the following Javascript to restrict a text field on my website to only accept numerical input, and no other letters or characters. The problem is, it REALLY reje

29条回答
  •  误落风尘
    2020-12-04 22:17

    Here is my solution: a combination of the working ones below.

    var checkInput = function(e) {
            if (!e) {
                e = window.event;
            }
    
            var code = e.keyCode || e.which;
    
            if (!e.ctrlKey) {
    
                //46, 8, 9, 27, 13 = backspace, delete, tab, escape, and enter
                if (code == 8 || code == 13 || code == 9 || code == 27 || code == 46)
                    return true;
                //35..39 - home, end, left, right
                if (code >= 35 && code <= 39)
                    return true;
                //numpad numbers
                if (code >= 96 && code <= 105)
                    return true;
                //keyboard numbers
                if (isNaN(parseInt(String.fromCharCode(code), 10))) {
                    e.preventDefault();
                    return false;
                }
            }
            return true;
        };
    

提交回复
热议问题