jquery限制文本框输入字符长度

来源:互联网 发布:超星慕课刷课软件 编辑:程序博客网 时间:2024/06/14 09:28

http://blog.csdn.net/phpfenghuo/article/details/42149741


js代码:

[javascript] view plain copy print?
  1. jQuery.fn.maxLength = function(max){  
  2.         this.each(function(){  
  3.             var type = this.tagName.toLowerCase();  
  4.             var inputType = this.type? this.type.toLowerCase() : null;  
  5.             if(type == "input" && inputType == "text" || inputType == "password"){  
  6.                 //Apply the standard maxLength  
  7.                 this.maxLength = max;  
  8.             }  
  9.             else if(type == "textarea"){  
  10.                 this.onkeypress = function(e){  
  11.                     var ob = e || event;  
  12.                     var keyCode = ob.keyCode;  
  13.                     var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;  
  14.                     return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);  
  15.                 };  
  16.                 this.onkeyup = function(){  
  17.                     if(this.value.length > max){  
  18.                         this.value = this.value.substring(0,max);  
  19.                     }  
  20.                 };  
  21.             }  
  22.         });  
  23.     };  
使用方法:
[javascript] view plain copy print?
  1. $('#phone').maxLength(4); 
原创粉丝点击