只允许使用javascript输入数字并允许复制和粘贴?

只允许使用javascript输入数字并允许复制和粘贴?

问题描述:

我正在使用此功能仅允许文本输入中的数字。

I'm using this function to only allow numbers in a text input.

$('input').bind('keydown', function(e) {

    var key = e.charCode || e.keyCode || 0;

    return (
         key == 8 ||
         key == 9 ||
         key == 46 ||
         (key >= 37 && key <= 40) ||
         (key >= 48 && key <= 57) ||
         (key >= 96 && key <= 105));
});

我如何才允许复制和粘贴?我已经尝试添加键码17进行控制,但它仍然不起作用。

How would I also allow copy and paste? I've tried adding keycode 17 for control but it still doesn't work.

键组合有什么特别之处吗?

Is there something special you have to do for key combinations?

谢谢

最好用以下的东西:

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

或者您也可以使用更改事件。在这种情况下,无论数据如何进入字段,都将进行验证(并删除非数字输入)。

Or you can also use the change event. In this case no matter how the data gets into the field it will be validated (and non numeric input removed). ​