替form中的文本框绑定验证最大长度事件(按字节)

为form中的文本框绑定验证最大长度事件(按字节)

 

/**  
 * 为form中的文本框绑定验证最大长度事件(按字节)  
 *   
 * @param fromName  
 */  
function bindMaxLength(fromName,height){   
    if(typeof(height) == "undefined"){   
        height = 16;   
    }   
    $("form[name="+fromName+"] input[type=text]").each(function(){   
        if(typeof ($(this).attr("maxlength"))!="undefined"){   
//          alert("width"+this.style.width);   
//          alert("width"+$(this).css("width")); //会取到默认宽度   
            //解决ie8下onpropertychange事件间歇性失效的问题   
            if(this.style.width != "" && this.style.height==""){   
                this.style.height = height+"px";   
            }   
            $(this).bind('input propertychange', function() {   
                    var inputLength = this.value.replace(/[^\x00-\xff]/g, 'xxx').length;   
                    var maxlength = parseInt($(this).attr("maxlength"));   
                    if(inputLength > maxlength){   
                        this.value = subStr(this.value,maxlength);   
                    }   
            });    
        }   
    });   
}  

 

/**  
 * 按字节截取字符串, 一个中文按3个字节算的  
 *   
 * @param str  
 * @param maxlength  
 * @returns  
 */  
function subStr(str,maxlength){   
    var len = 0;   
    // 我ab   
    for(var i=0; i<str.length; i++){   
        len += (str.charCodeAt(i)>255 ? 3 : 1);   
        if(len>maxlength){   
            return str.substring(0,i);   
        }   
    }   
    return str;   
}