如何忽略文本框中不需要的字符(JavaScript或jQuery)

有一个TextBox,我想让用户只输入数字而不是任何字母字符。 那么我怎么能忽略最终用户通过JavaScript或jQuery输入的那些字符呢? 注意我不想用空字符串替换用户输入的值; 相反,如果有任何办法可以忽略案例。

尝试该代码:

$("#id").keypress(function (e) { //if the letter is not digit then display error and don't type anything if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) { return false; } }); 

参考“ http://roshanbh.com.np/2008/04/textbox-accept-only-numbers-digits.html

我不建议拦截击键,允许用户键入他/她想要的任何内容,并validation用户操作(提交/选择等)。

看看这个jQuery插件,例如: http : //bassistance.de/jquery-plugins/jquery-plugin-validation/

你说你不想包括字母表然后你说你只想忽略案例? 你需要做什么?

您可以使用string.toLowerCase()忽略JS中的string.toLowerCase()

您想要将处理程序附加到文本框的keypress事件。 在这里检查event.which属性以找出按下的键,如果它不是数字(在键码48和57之间)返回false,这将取消在文本框中键入的默认行为。

 $("input").keypress(function (e) { if (e.which < 48 || e.which > 57) return false; }); 

仅限数字我使用此jquery扩展/插件

http://www.texotela.co.uk/code/jquery/numeric/