Disable copy paste of alphabets in text field using jquery

后端 未结 6 1855
遇见更好的自我
遇见更好的自我 2021-01-14 05:33

In my project i have text field that only take numeric value.but when I copy an alphabets using ctl+c and paste using ctl+v it will allow the alphabets in the text field.So

6条回答
  •  北荒
    北荒 (楼主)
    2021-01-14 06:05

    Try this function. This may not be what you are looking for but you can do something out of this. I have done this earlier and posted on my blog.

    JS:

     $(function(){  
                    $(".numericOnly").bind('keypress',function(e){  
                              if(e.keyCode == '9' || e.keyCode == '16'){  
                                    return;  
                               }  
                               var code;  
                               if (e.keyCode) code = e.keyCode;  
                               else if (e.which) code = e.which;   
                               if(e.which == 46)  
                                    return false;  
                               if (code == 8 || code == 46)  
                                    return true;  
                               if (code < 48 || code > 57)  
                                    return false;  
                         }  
                    );  
                    $(".numericOnly").bind("paste",function(e) {  
                         e.preventDefault();  
                    });  
                    $(".numericOnly").bind('mouseenter',function(e){  
                          var val = $(this).val();  
                          if (val!='0'){  
                               val=val.replace(/[^0-9]+/g, "")  
                               $(this).val(val);  
                          }  
                    });  
               });  
    

    HTML:

       
             
       
    

    This will allow you to enter only numeric values only. You can't even copy paste and drag drop.

    DEMO

    Code Link

提交回复
热议问题