只允许使用javascript输入数字并允许复制和粘贴? [英] Only allow numbers in an input with javascript and allow copy and paste?

查看:66
本文介绍了只允许使用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). ​

这篇关于只允许使用javascript输入数字并允许复制和粘贴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆