当用户满足文本框的最大长度时显示对话框

Display Dialog Box When User Meets MaxLength of TextBox

本文关键字:显示 对话框 满足 用户 文本      更新时间:2023-09-26

我有一个asp.net c#应用。我有一个TextBox的MaxLength设置为3000。当用户达到最大长度3000时,我想要一个JavaScript对话框打开并更改此用户。我不知道该怎么做。有人能帮我吗?谢谢。

From aspdotnet-suresh:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Limit the number of characters in textbox or textarea</title>
<script type="text/javascript">
function LimtCharacters(txtMsg, CharLength, indicator) 
{
    chars = txtMsg.value.length;
    document.getElementById(indicator).innerHTML = CharLength - chars;
    if (chars > CharLength) 
    {
        txtMsg.value = txtMsg.value.substring(0, CharLength);
    }
}
</script>
</head>
<body>
<div style="font-family:Verdana; font-size:13px">
Number of Characters Left:
<label id="lblcount" style="background-color:#E2EEF1;color:Red;font-weight:bold;">3000</label><br/>
<textarea id="mytextbox" rows="5" cols="25" onkeyup="LimtCharacters(this,3000,'lblcount');"></textarea>
</div>
</body>
</html>

您可以使用您的文本框的TextChanged事件。在处理程序中,您可以简单地检查TextBox.Text属性的长度,并在达到最大长度时显示一个MessageBox,如下所示:

Response.Write(string.Format("<script>alert('{0}');</script>", message));

你可以用这个JavaScript来限制字符的数量

<script language="javascript" type="text/javascript">
        function limitText(Field, limitNum) {
            if (Field.value.length > limitNum) {
                Field.value = Field.value.substring(0, limitNum);
            }
        }
    </script>

<asp:FormView runat="server">
    <ItemTemplate>
        <b>Something</b>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" onKeyDown="limitText(this,3000);"
            onKeyUp="limitText(this,3000);"></asp:TextBox>
    </EditItemTemplate>
</asp:FormView>

或显示警告,

<input type="text"  onkeydown="return testLength()" id="txtBox" />
function testLength(){
   var e = document.getElementById('txtBox');
   if(e.value.length>6)
   {
      alert('you have entered more than 3000 characters');
      // Set value back to the first 6 characters 
      e.value = e.value.substring(0, 3000);
   }
   return true;
}