0

I am using a syntax like this

if(e.keycode  == 17 ....
   e.preventDefault()

and works for all keys controls, alts, tabs and etc all but one the space which the keycode is 38 I want to prevent the user from typing whitespaces in a textbox

4

2 回答 2

2

您可以阻止用户键入这样的空格,false如果键码返回则32返回true

$("input").on("keydown", function (e) {
    return e.which !== 32;
});

JS 小提琴示例

注意:您提到了键码 38,但这是用于UP箭头键而不是Space

这是Key Code的列表,但不幸的是作者没有在此列表中包含空间的 Key code :)

于 2013-04-09T19:26:25.800 回答
0

你可以使用 jquery 来做到这一点。请在这里查看我的样品。 http://jsfiddle.net/SinPride/9P29p/

<input type="text" id="txt_name">
<script>
$('#txt_name').keypress(function( e ) {
    if(e.which === 32) 
        return false;
});
</script>
于 2013-04-09T19:30:01.037 回答