addEventListener 中按键事件的问题...仅限制输入字符
我放置了一个文本框....我想对其进行限制..
不允许在文本框中输入数字和特殊字符...
我该如何在Javascript中使用onkeypress事件???
我的代码是...
<script>
function event()
{
document.getElementById("TX1").addEventListener("keypress", handleKeyPress, false);
}
function handleKeyPress(e)
{
var restricted = "0123456789_#!";
var key = e.keyCode || e.which;
var i=0;
for(;i<restricted.length;i++)
{
if (restricted.charCodeAt(i) == key)
{
e.returnValue = false;
}
return true;
}
</script>
<body onLoad="event();">
<input type="text" name="T1" id="TX1" size="27" maxlength="35" >
</body>
I have placed one textbox.... I want to put restriction on it ..
that digits and special characters should not be allowed to input in textbox...
how can i do using onkeypress event in Javascript ???
my code is ...
<script>
function event()
{
document.getElementById("TX1").addEventListener("keypress", handleKeyPress, false);
}
function handleKeyPress(e)
{
var restricted = "0123456789_#!";
var key = e.keyCode || e.which;
var i=0;
for(;i<restricted.length;i++)
{
if (restricted.charCodeAt(i) == key)
{
e.returnValue = false;
}
return true;
}
</script>
<body onLoad="event();">
<input type="text" name="T1" id="TX1" size="27" maxlength="35" >
</body>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要通过
keypress
过滤来执行此操作。它对用户不利、令人困惑、搞乱其他控制按键,并且很容易通过使用其他输入方法(例如复制/粘贴、拖/放、表单填充器、拼写检查器、IME)来击败它......相反,有一个明显的警告当用户放入意外内容时指示用户,例如:
如果需要,您可以使用
addEventListener
作为事件附件,但请注意,这在 IE<9 中不起作用,对于 IE<9您将需要attachEvent
模型。 (event.returnValue
特定于 IEattachEvent
模型,不能与addEventListener
一起使用,后者使用event.preventDefault()< /code> 相反。)
Don't do this through
keypress
filtering. It's user-hostile, confusing, messes up other control keypresses and is easy to defeat by using other methods of input, such as copy/paste, drag/drop, form fillers, spellcheckers, IMEs...Instead, have a warning that visibly directs the user when they've put something unexpected in, eg.:
You can use
addEventListener
for the event attachment if you want to, but be aware this won't work in IE<9, for which you would need theattachEvent
model. (event.returnValue
is specific to the IEattachEvent
model and will not work withaddEventListener
, which usesevent.preventDefault()
instead.)请尝试以下操作:
Try the following: