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.
这篇关于为多行文本框指定最大长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为多行文本框指定最大长度
基础教程推荐
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
