哪种方法可以过滤文本字段的数值?

我正在开发一个文本字段,使用那种不允许您输入数字值以外的validation。 因此,我的初始代码看起来很简单,与此类似:

$(textField).onKeyPress(function(e) { if (e.which  57) e.preventDefault(); }); 

这是非常明确的,但转向(在所有浏览器的最新版本中)Firefox也会使用箭头键和删除/退格键来阻止移动,而其他浏览器则不会。

环顾四周,我发现我还需要检查这些键,并检查e事件参考中公开的不同属性。

我的最终代码看起来像这样:

 $(textField).onKeyPress(function(e) { var code = e.which || e.keyCode; if (code > 31 // is not a control key && (code  40) // is not an arrow key && (code  57) // is not numeric && (code != 46) // is not the delete key ) e.preventDefault(); }); 

然而,这对于解决一个相当简单的问题感觉太多了,因为只是防止非数字化。

我究竟做错了什么? 就这种validation而言,哪种方法最佳?

我们将响应两个按键和模糊事件。 当某人按下某个键时,我们会检查输入的密钥是否为数字。 如果是,我们允许。 否则,我们会阻止它。

如果字段模糊,我们会删除所有非数值以及后面的所有值。 这将阻止用户粘贴非数字字符串:

 $("#textfield").on("keypress blur", function(e){ if ( e.type === "keypress" ) return !!String.fromCharCode(e.which).match(/^\d$/); this.value = this.value.replace(/[^\d].+/, ""); }); 

演示: http : //jsfiddle.net/jonathansampson/S7VhV/5/

工作演示 http://jsfiddle.net/Pb2eR/23/ 更新了复制/粘贴演示: http : //jsfiddle.net/Pb2eR/47/ (在这个演示机智中,您复制粘贴字符串,其中包含不允许使用的字符)允许复制粘贴号码:在safari中测试)

演示箭头键工作 http://jsfiddle.net/gpAUf/

这对你有所帮助。

注意:在这个版本中,即使你复制粘贴它也会将其设置为空输入框,在safari lion osx中测试:)

好的链接:[1] 如何使用jQuery仅允许HTML输入框中的数字(0-9)?

 $(".hulk").keyup(function(){ this.value = this.value.replace(/[^0-9\.]/g,''); });​ 

HTML

  

复制粘贴内容的更新

 $(".hulk").keyup(function(){ this.value = this.value.replace(/[^0-9\.]/g,''); }); $(".hulk").bind('input propertychange', function() { this.value = this.value.replace(/[^0-9\.]/g,''); });​ 

另一个演示的代码

 $(".hulk").bind('input propertychange', function(event) { if( !(event.keyCode == 8 // backspace || event.keyCode == 46 // delete || (event.keyCode >= 35 && event.keyCode <= 40) // arrow keys/home/end || (event.keyCode >= 48 && event.keyCode <= 57) // numbers on keyboard || (event.keyCode >= 96 && event.keyCode <= 105)) // number on keypad ) { event.preventDefault(); // Prevent character input } this.value = this.value.replace(/[^0-9\.]/g,''); });​ 

这将允许两个int。 如果用户使用鼠标复制和粘贴,它也会删除文本。

 $(document).ready(function () { $('#textfield').bind('keyup blur', function (e) { if (e.type == 'keyup') { if (parseInt($(this).val()) != $(this).val()) { $(this).val($(this).val().slice(0, $(this).val().length - 1)); } } else if (e.type == 'blur') { $(this).val(''); } }); });