HTML5 restricting input characters

2019-02-16 08:41发布

Is it possible to restrict the input of certain characters in HTML5/JavaScript? For example could I have a input textbox on the screen and if the user tries to type a letter it wouldn't show up in the box because I've restricted it to only numbers?

I know you can use pattern which will check on submit, but I want the "bad" characters to just never be entered at all.

7条回答
太酷不给撩
2楼-- · 2019-02-16 09:42

The input textbox

<input type="text" onKeyDown="myFunction()" value="" />

JavaScript

function myFunction() {
    var e = event || window.event;  // get event object
    var key = e.keyCode || e.which; // get key cross-browser

    if (key < 48 || key > 57) { //if it is not a number ascii code
        //Prevent default action, which is inserting character
        if (e.preventDefault) e.preventDefault(); //normal browsers
            e.returnValue = false; //IE
    }
}
查看更多
登录 后发表回答