Best way to restrict a text field to numbers only?

前端 未结 29 1689
长情又很酷
长情又很酷 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:39

    I use this:

        oEl.keypress(function(ev)
        {
            var sKey = String.fromCharCode(ev.which);
            if (!sKey.match(/[0-9]/) || !sKey === "") 
                ev.preventDefault();            
        });
    

    The advantage is, that every key which does not provide an input to the field is still allowed, so you don't have to worry about every single special key. Even combos like CTRL + R do still work.

    EDIT As this is not working in Firefox I had to modify the function a little:

        oEl.keypress(function(ev)
        {
            var iKeyCode = ev.which || ev.keyCode;
            var aSpecialKeysForFirefox = [8, 9, 13, 27, 37, 38, 39, 40, 46];
            var sKey = String.fromCharCode(iKeyCode);
            if (sKey !== "" && $.inArray(iKeyCode, aSpecialKeysForFirefox ) < 0 && !sKey.match(/[0-9]/)) {
                ev.preventDefault();
            }
        });
    

    Explanation All Browsers handle jquerys keypress event differently. To make it work in FF the $.inArray check is added. As firefoxs keypress-event doesn't trigger when combinations like strg+tab are used, but the others do, the key.match approach still adds a little value to the latter, as it enables those combinations.

提交回复
热议问题