Pages

Thursday, August 4, 2011

Prevent copy paste on input : allow only numeric values jQuery


The following example won't allow values other than numeric.
  1. From keyboard (even copy paste)
  2. From drag drop
  3. From mouse (copy paste)
Demo : Try demo here
 <!DOCTYPE html>  
 <html>  
      <head>  
           <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />  
           <title>jQuery UI Example Page</title>  
           <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>  
           <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>  
      </head>  
      <body>  
           <input type="text" id="textBox" class="numericOnly" />  
      </body>  
      <script type="text/javascript">  
           $(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);  
                      }  
                });  
           });  
      </script>  
 </html>  

1 comment: