多行文本框的字符数限制。

   在Web开发中经常会遇到多行文本框,比如:备注栏。普通的文本框控件如果想要限制字符长度可以直接设置maxLength属性,但是,一旦将文本框设置为多行,虽说也可以设置maxLength属性,但是我们会发现这个功能已经失效了,于是我找了个新的方法,比较复杂了点,希望大家有好的意见可以给我提。

 

1.首先在<head></head>中添加下列js脚本:

 

function setMaxLength(object,length) 

var result = true
var controlid = document.selection.createRange().parentElement().id; 
var controlValue = document.selection.createRange().text; 
if (controlid == object.id && controlValue != ""

result 
= true
}
 
else if (object.value.length >= length) 

result 
= false
}
 
if (window.event) 

window.event.returnValue 
= result; 
return result; 
}
 
}
 

//Check maxlength for multiline TextBox when paste 
function limitPaste(object,length) 

var tempLength = 0
if(document.selection) 

if(document.selection.createRange().parentElement().id == object.id) 

tempLength 
= document.selection.createRange().text.length; 
}
 
}
 
var tempValue = window.clipboardData.getData("Text"); 
tempLength 
= object.value.length + tempValue.length - tempLength; 
if (tempLength > length) 

tempLength 
-= length; 
tempValue 
= tempValue.substr(0,tempValue.length - tempLength); 
window.clipboardData.setData(
"Text", tempValue); 
}
 

window.event.returnValue 
= true
}
 

 

2.在需要限制大小的文本框内添加下列属性:

 onkeypress="javascript:setMaxLength(this,100);" onpaste="limitPaste(this, 100)"

其中的100是字符大小(注:汉字计入1个字符,100也就是指100个汉字或英文字母)

 

有可能大家在.NET的服务器控件上添加以上代码时会提示说不含此属性,不用管它,直接运行就可以达到效果。

 

posted @ 2008-09-10 11:25  漂_泊  阅读(1486)  评论(0编辑  收藏  举报