限制textbox或textarea輸入字符長度的JS代碼
更新時間:2013年10月16日 08:34:05 作者:
textbox或textarea的輸入字符限制有很多方法,在本將為大家詳細介紹下js中時如何實現(xiàn)的,感興趣的朋友不要錯過
復制代碼 代碼如下:
<script language=javascript>
<!--
String.prototype.len=function(){
return this.replace(/[^\x00-\xff]/g,"**").length;
}
//Set maxlength for multiline TextBox
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.len() >= 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.len();
}
}
var tempValue = window.clipboardData.getData("Text");
tempLength = object.value.len() + tempValue.len() - tempLength;
if (tempLength > length)
{
tempLength -= length;
//alert(tempLength);
//alert(tempValue);
var tt="";
for(var i=0;i<tempValue.len()-tempLength;i++)
{
if(tt.len()<(tempValue.len()-tempLength))
tt=tempValue.substr(0,i+1);
else
break;
}
tempValue=tt;
window.clipboardData.setData("Text", tempValue);
}
window.event.returnValue = true;
}
//-->
</script>
然后設多行的textbox或textarea的2個屬性.
onkeypress="javascript:setMaxLength(this,100);" onpaste="limitPaste(this, 100)"
現(xiàn)在好了,可以自動區(qū)分中英文了,這個方案不錯,供大家分享
相關文章
基于JavaScript 性能優(yōu)化技巧心得(分享)
下面小編就為大家分享一篇基于JavaScript 性能優(yōu)化技巧心得,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12
JavaScript原生開發(fā)視頻播放器的實現(xiàn)代碼
這篇文章我們將一起探索一份自定義的視頻播放器實現(xiàn)代碼,甚至還可以實現(xiàn)有彈幕功能,文中的示例代碼講解詳細,感興趣的可以了解一下2023-06-06

