<script type="text/javascript">
$(function(){
jQuery.fn.maxLength=function(max){
return this.each(function(){
var type=this.tagName.toLowerCase();
var inputType=this.type?this.type.toLowerCase:null;
if(type==‘input‘&&inputType=="text"||inputType=="password"){
this.maxLength=max;
}else if (type=="textarea") {
this.onkeypress=function(e){
var obj=e||event;
var keyCode=obj.keyCode;
this.onkeyup=function(){
if (this.value.length>max) {
this.value=this.value.substring(0,max);
}
}
}
}
})
};
$("#btn").click(function(){
var vMaxLen=$("input#txt").val();
var iMaxLen=parseInt(vMaxLen);
$("#txtarea").maxLength(iMaxLen);
$("#log").html($("#log").html()+"<p>"+"最大字符个数设定为:"+vMaxLen+"个"+"</p>");
});
});
</script>
</head>
<body>
<p>
<b>最大输入字符个数</b>
<input type="text" id="txt" style="width: 32px;" value="10"/>
</p>
<p>
<input type="button" id="btn" value="限制文本域中字符的个数"/>
</p>
<div>
<textarea rows="" cols="" id="txtarea" name="maxLenTextarrea"></textarea>
</div>
<div id="log">
<p>日志记录:</p>
</div>
时间: 2024-12-13 11:34:31