简体   繁体   中英

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"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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