我想禁止用户在 HTML 文本输入字段中输入非字母或数字的字符。
这个确切的功能可以在 Twitter 注册页面(用户名字段)https://twitter.com/signup 上看到。 .
我正在尝试用 jQuery 编写这个。但我需要能够获取传入的按键事件值来测试按下了哪个键以及其值是否可接受。
代码如下:
<input type="text" id="username" name="username" />
<script type="text/javascript">
$("#username").keypress(function(event){
// Get the keypress value
// ...?
// If the keypress value is illegal then disable it
if (...){
event.preventDefault();
}
});
</script>
最佳答案
您可以使用事件对象的“which”属性来捕获键码。您可以使用类似以下代码的内容来获取相应的字符 -
var c = String.fromCharCode(e.which);
查看链接http://api.jquery.com/keypress/详细解释。
关于jquery - 如何从 jQuery 中的事件对象获取按键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/874158/