简体   繁体   English

输入禁用复制和粘贴上的文本输入

[英]input disable text entry on copy and paste

The following function works well, however it currently stops pasting text and number. 下面的函数运行良好,但是当前停止粘贴文本和数字。 Is there a way of stopping only text inside the input? 有没有一种方法可以只停止输入内容中的文本?

var restrictInputToDigits = function(){
    $('.digits').keypress(function(key) {
        if(key.charCode < 48 || key.charCode > 57) return false;
    });
    $('.digits').bind('copy paste', function (e) {
         e.preventDefault();
    });
}

I would like digits to be pasted in as well. 我也希望粘贴数字。

First get the value of text field. 首先获取文本字段的值。 Then replace all characters except number by empty character. 然后将除数字以外的所有字符替换为空字符。 This should help 这应该有帮助

 $('.digits').on('change keyup',function(){ var value = $(this).val().toString().replace(/[^0-9]/g, ''); $(this).val(value); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <input type="text" class="digits"> 

 $('.digits').on('change keyup paste', function(e){ $this = $(this); $this.val($this.val().replace(/\\D+/, '')); if(e.charCode < 48 || e.charCode > 57){ e.preventDefault(); return false; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input class="digits" value="1234"> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM