为多行文本框指定最大长度 [英] Specifying maxlength for multiline textbox

查看:25
本文介绍了为多行文本框指定最大长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆