HTML text input allow only numeric input

前端 未结 30 3523
孤街浪徒
孤街浪徒 2020-11-21 04:58

Is there a quick way to set an HTML text input () to only allow numeric keystrokes (plus \'.\')?

30条回答
  •  鱼传尺愫
    2020-11-21 05:27

    JavaScript code:

    function validate(evt)
    {
        if(evt.keyCode!=8)
        {
            var theEvent = evt || window.event;
            var key = theEvent.keyCode || theEvent.which;
            key = String.fromCharCode(key);
            var regex = /[0-9]|\./;
            if (!regex.test(key))
            {
                theEvent.returnValue = false;
    
                if (theEvent.preventDefault)
                    theEvent.preventDefault();
                }
            }
        }
    

    HTML code:

    
    

    works perfectly because the backspace keycode is 8 and a regex expression doesn't let it, so it's an easy way to bypass the bug :)

提交回复
热议问题