I'm using the following Javascript to restrict a text field on my website to only accept numerical input, and no other letters or characters. The problem is, it REALLY rejects all other key inputs, like ctrl-A to select the text, or even any other browser functions like ctrl-T or ctrl-W while the text box is selected. Does anyone know of a better script to only allow numerical input, but not block normal commands (that aren't being directly input into the field)? Thanks
Here is the code I'm using now:
function numbersonly(e, decimal)
{
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27))
return true;
else if ((("0123456789").indexOf(keychar) > -1))
return true;
else if (decimal && (keychar == "."))
return true;
else
return false;
}
Edit: None of the solutions provided have solved my problem of allowing commands like ctrl-A while the text box is selected. That was the whole point of my asking here, so I have gone back to using my original script. Oh well.
这是我再次为数字制作的东西,它也将允许所有格式化程序。
jQuery
$('input').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
if (!(a.indexOf(k)>=0))
e.preventDefault();
});
Try it
http://jsfiddle.net/zpg8k/ http://jsfiddle.net/zpg8k/
请注意,您还需要在提交/服务器端进行过滤,以便粘贴/上下文菜单和不支持粘贴事件的浏览器。
编辑以详细说明多种方法
我看到你在“接受”的答案上徘徊,所以我会澄清一些事情。您确实可以使用此处列出的任何方法,它们都有效。我个人做的是使用我的进行实时客户端过滤,然后在提交和服务器端按照其他人的建议使用正则表达式。然而,任何客户端本身都不会 100% 有效因为没有什么可以阻止我投入document.getElementById('theInput').value = 'Hey, letters.';
在控制台中并绕过任何客户端验证(轮询除外,但我可以取消setInterval
也从控制台)。使用您喜欢的任何客户端解决方案,但请确保您也在提交和服务器端实现了某些功能。
编辑 2 - @Tim Down
好吧,根据评论,我必须调整两件我没有想到的事情。首先,keypress 而不是 keydown,后者已更新,但 IE 中缺少 indexOf(认真的微软!?)也破坏了上面的示例。这是一个替代方案
$('input').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
if (!($.inArray(k,a)>=0))
e.preventDefault();
});
新的jsfiddle:http://jsfiddle.net/umNuB/ http://jsfiddle.net/umNuB/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)