jquery - 鼠标右键粘贴在所有浏览器中只允许数字

标签 jquery

我有输入框 jsfiddle 链接,其中包含我所做的示例代码 https://jsfiddle.net/4rsv960t/173/ 我想允许仅包含数字的粘贴事件(如果它不是数字),然后自动清空文本框。

仅允许编号我的示例代码

$(".allownumericwithoutdecimal").on("keypress keyup blur",function (event) {
      console.log('allownumericwithoutdecimal called');
      $(this).val($(this).val().replace(/[^\d].+/, ""));
        if ((event.which < 48 || event.which > 57)) {
            event.preventDefault();
        }
     });

 <input type="text" value="" class="allownumericwithoutdecimal"/>

最佳答案

就这么简单

$(".allownumericwithoutdecimal").on("input", function(event) {
  this.value = /^\d+$/.test(this.value) ? this.value : "";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="" class="allownumericwithoutdecimal" />

或者保留数字

$(".allownumericwithoutdecimal").on("input", function(event) {
  this.value = this.value.replace(/\D/g, "");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="" class="allownumericwithoutdecimal" />

关于jquery - 鼠标右键粘贴在所有浏览器中只允许数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51264926/

相关文章:

javascript - 无法从输入类型数值中删除逗号

javascript - 检查 jQuery 或 Javascript 中哈希数组中某些值的存在

javascript - 制作用户访问弹出窗口

jquery - 如何在 HTML 中使用 LoadGo 动画

javascript - 使用Jquery根据条件动态添加cssClass

javascript - 之前的 Jquery 事件设置了未定义的值

javascript - jQuery 将变量内容添加到 DIV 中

javascript - jQuery 未在 ajax 请求的脚本标记中加载 js 文件

javascript - AngularJS:有没有办法知道另一个指令中包含的指令何时加载?

javascript - 在 jQuery 中订阅 "childrenAdded"事件