为多行文本框指定最大长度

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.

这篇关于为多行文本框指定最大长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)
Bind multiple parameters from route and body to a model in ASP.NET Core(在ASP.NET Core中将路由和主体中的多个参数绑定到一个模型)
Custom model binding in AspNet Core WebApi?(AspNet Core WebApi中的自定义模型绑定?)
Parse multiline log entries using a regex(使用正则表达式解析多行日志条目)