javascript limit text input characters

前端 未结 5 1276
攒了一身酷
攒了一身酷 2020-12-22 06:30

I am wanting to restrict the input characters for a text box to [a-z0-9_-]. However whenever if do this buttons like backspace and the arrow keys don\'t work. I have found s

5条回答
  •  被撕碎了的回忆
    2020-12-22 07:17

    Add this code to onkeypress event.

        var code;
        document.all ? code = e.keyCode : code = e.which;
        return ((code > 64 && code < 91) || (code > 96 && code < 123) || code == 8 || code == 32 || (code >= 48 && code <= 57));
    

    For browser compatibility, You can add var k = e.keyCode == 0 ? e.charCode : e.keyCode;

提交回复
热议问题