Character Limiting in TextBox in ASP.NET Using JQuery and Display Red When Reaches Out of Limit


Introduction

Look at the images given blow that you frequently see on websites. In this article you are going to learn hoe to do this.

image001.jpg
The screen when the character length exceeds the limit:

  image002.jpg
Follow the steps to create such a system.

Step 1:

Add the reference of the jQuery file in the head section of the web page, for example:

    <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>

Step 2:

Add the following jQuery method in the head section of the web page:

    <script type="text/javascript" language="javascript">
        $(document).ready(function () {
            var txt = $("textarea[id$=txtComments]");
            var txtMsg = $("label[id$=txtStatus]");
            $(txt).keyup(function () {
                var length = $(txt).val().length;
                $(txtMsg).text("Total " + length + " Characters out of 200.");
                $(txtMsg).css("background-color", length >= 201 ? "#FF0000" : "#FFFFFF");
            });
        });
    </script>

Step 3:

Design the web page which contains TextBox, Label and a Button; for example:

    <div>
    Enter your comment
    <br />
    <asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Height="164px" Width="298px"/>
    <br />
    <label id="txtStatus"></label>
    <br />
        <asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" />
    </div>

Now look at my complete coding.

Complete Code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ASP.NET & jQuery Post</title>
    <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
    <script type="text/javascript" language="javascript">
        $(document).ready(function () {
            var txt = $("textarea[id$=txtComments]");
            var txtMsg = $("label[id$=txtStatus]");
            $(txt).keyup(function () {
                var length = $(txt).val().length;
                $(txtMsg).text("Total " + length + " Characters out of 200.");
                $(txtMsg).css("background-color", length >= 201 ? "#FF0000" : "#FFFFFF");
            });
        });
    </script>
</head>
<
body>
    <form id="form1" runat="server">
    <div>
    Enter your comment
    <br />
    <asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Height="164px" Width="298px"/>
    <br />
    <label id="txtStatus"></label>
    <br />
        <asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" />
    </div>
    </form>
</body>
</
html>

I recommend that you to download the attached file and check it. I hope you like it. Thanks.