Specifying maxlength for multiline textbox(为多行文本框指定最大长度)
问题描述
我正在尝试使用asp:
I'm trying to use asp:
<asp:TextBox ID="txtInput" runat="server" TextMode="MultiLine"></asp:TextBox>
我想要一种方法来指定 maxlength 属性,但显然 multiline textbox 是不可能的.我一直在尝试为 onkeypress 事件使用一些 JavaScript:
I want a way to specify the maxlength property, but apparently there's no way possible for a multiline textbox. I've been trying to use some JavaScript for the onkeypress event:
onkeypress="return textboxMultilineMaxNumber(this,maxlength)"
function textboxMultilineMaxNumber(txt, maxLen) {
try {
if (txt.value.length > (maxLen - 1)) return false;
} catch (e) { }
return true;
}
虽然这个 JavaScript 函数工作正常,但问题在于,在写入字符后,它不允许您删除和替换其中的任何字符,这种行为是不希望的.
While working fine the problem with this JavaScript function is that after writing characters it doesn't allow you to delete and substitute any of them, that behavior is not desired.
你知道我可以在上面的代码中改变什么来避免这种情况或任何其他方法来绕过它吗?
Have you got any idea what could I possibly change in the above code to avoid that or any other ways to get round it?
推荐答案
试试这个 javascript:
try this javascript:
function checkTextAreaMaxLength(textBox,e, length)
{
var mLen = textBox["MaxLength"];
if(null==mLen)
mLen=length;
var maxLength = parseInt(mLen);
if(!checkSpecialKeys(e))
{
if(textBox.value.length > maxLength-1)
{
if(window.event)//IE
e.returnValue = false;
else//Firefox
e.preventDefault();
}
}
}
function checkSpecialKeys(e)
{
if(e.keyCode !=8 && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
return false;
else
return true;
}
在控件上像这样调用它:
On the control invoke it like this:
<asp:TextBox Rows="5" Columns="80" ID="txtCommentsForSearch" MaxLength='1999' onkeyDown="checkTextAreaMaxLength(this,event,'1999');" TextMode="multiLine" runat="server"> </asp:TextBox>
您也可以只使用 checkSpecialKeys 函数来验证您的 javascript 实现中的输入.
You could also just use the checkSpecialKeys function to validate the input on your javascript implementation.
这篇关于为多行文本框指定最大长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为多行文本框指定最大长度
基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
