且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何仅允许文本输入中的数字但允许使用JavaScript命令?

更新时间:2022-11-26 17:32:33

我实际上是为了我允许用户键入/输入他们想要的任何内容的方法,并手动将值强制为数字。像这样的东西(这是一个jQuery项目,但这个想法很容易被jQuery重用)。

I actually went for an approach where I let the user type / enter whatever they want to, and manually coerce the value to be a numeric. Something like this (it's a jQuery project, but the idea can easily be re-used w/o jQuery).

fieldJq.bind('click keyup change blur focus', function (ev) {
  var curVal = $(this).val();
  $(this).val(curVal.replace(/[^0-9\.]/g, ''));
});

这里的想法是我让他们把任何他们想要的东西放入其中(所以没有破坏控制命令的可能性,如复制/粘贴等)但在更改任何值后,我删除任何不是数字或小数点的内容。此时不是100%防火(10.0.0无效),但它最初确实至少接近。如果您不需要浮点支持并且可以从正则表达式中删除 \。,那么您将获得强制数字输入。

The idea here being that I'm letting them put whatever they want to into it (so there's no chance of breaking control commands like copy / paste, etc) but after any value change to it I remove anything that's not a digit or a decimal point. It's not 100% fireproof at this point (10.0.0 isn't invalid) but it does come close initially at least. If you didn't need floating point support and could remove the \. from the regex you'd have an enforced numeric input.