{infiniteZest}
// Articles. Tutorials. Utilities.
Home  |   Search  |   Login  
Categories Skip Navigation Links
New / All
AJAX
Apple
ASP.NET
.NET
Git
Google / Android
Python / IronPython
Miscellaneous
SQL Server
Adding real-time AJAX character counting to textboxes
Summary
It would be very useful to have counter right next to the textbox and increase that number as the user is typing into that textbox. Based on the lengths of the string entered into the textbox we could change the background of the textbox (white, yellow, red). This can be done in JavaScript (on MS AJAX) with relatively a few lines of client-side code.
 
Table of Contents

The Scenario

The User Interface

Adding the JavaScript code via asp.net page

Discussion of the JavaScript code

First, get the run-time id of the textbox.

Then add the client-sie event handlers.

Now the actual character counting method.

Finally, add the JavaScript to the page.

Generated JavaScript

The MS AJAX piece above

Enhanced Scenario and Methods

Figure 1. Character Counting with AJAX

The Enhanced User Interface

The Extended set of Character Counting methods

Figure 2. Character Counting with AJAX Explained

 

The Scenario

We want a character counter next to the textbox, which gets updated as the user enters text into the textbox. Depending on the length of the textbox, the background color of the textbox is changed.

First let’s look at a simple scenario:

  • One textbox
  • One character counter
  • Hard-coded lengths for when to make the textbox background white, yellow, and red.

The User Interface

The textbox is the straight-forward asp.net textbox:

t;asp:TextBox ID="txtCharCount1" runat="server"></asp:TextBox>

The counter is a div. We will putting a number inside this div, based on the length of the string entered into the above textbox:

<div id="CharCount1">
</div>

Above div has an id so that this div can be accessed later.

Adding the JavaScript code via asp.net page

Now let’s prepare and add the JavaScript/MS AJAX code via the ASP.NET page. The AddCharCount() method below has the .net code that adds the necessary JavaScript methods. This method can be called from the Page_Load().

/// <summary>
/// Makes the MS AJAX JavaScript code for counting
/// the characters in in a text box as they are entered.
/// </summary>
private void AddCharCount()
{
    // Need to get the unique id of the textbox.
    // Name of the HTML Input finally rendered on the page
    // may be prepended with containing elements.
    string txtID = txtCharCount1.UniqueID;

    // String that contains the necessary JavaScript methods
    string countChars = @"
        // Add the handlers
        function pageLoad()
        {
           $addHandler($get(’" + txtID + @"’), ’keyup’, CountChars);
        }

        // Method that counts the characters
        function CountChars()
        {
            // Obtain the length of the string in the textbox.
            var txtBox = $get(’" + txtID + @"’);
            var count = txtBox.value.length;

            // Update that number in the div
            $get(’CharCount1’).innerHTML = count;
 
            // Change the background color of the textbox
            // according to the length of the string.
            if (count < 5)
                txtBox.style.backgroundColor = ’white’
            else if((count > 4) && (count < 10))
                txtBox.style.backgroundColor = ’yellow’
            else
                txtBox.style.backgroundColor = ’red’
        }
        ";

    // If you want the <script></script> attached to the above
    // JavaScript code, add the last parameter (true) to the
    // RegisterClientScriptBlock method.
    // If you want to manually add the <script></script> enclosures
    // use the commented method below.
    ClientScript.RegisterClientScriptBlock(this.GetType(), "CountChars", countChars, true);
    //ClientScript.RegisterClientScriptBlock(this.GetType(), "CountChars", countChars);
}

Discussion of the JavaScript code

First, get the run-time id of the textbox.

The asp.net id of the textbox here is txtCharCount1; however, at run-time, that id might be prefixed with the containing elements. So, by using UniqueID property, get the run-time id.

    // Need to get the unique id of the textbox.
    // Name of the HTML Input finally rendered on the page
    // may be prepended with containing elements.
    string txtID = txtCharCount1.UniqueID;

Then add the client-sie event handlers.

In this case, our handler will run on the keyup event. This is the better event over keypress and keydown events. The keypress event will not fire for keys like backspace and keydown fires right after a key is pressed. In that case, the last key pressed will not be accounted for.

        // Add the handlers
        function pageLoad()
        {
           $addHandler($get(’" + txtID + @"’), ’keyup’, CountChars);
        }

Now the actual character counting method.

In this method, we will get the length of the string entered into the textbox and update our div (with ID CharCount1). Then based on the length of the string, we will change the background color of the textbox.

If the length is less than 5, then the background color is 5; if it’s between 5 and 10, the background color is yellow. And, if it’s more than 10, the background color is red.

        // Method that counts the characters
        function CountChars()
        {
            // Obtain the length of the string in the textbox.
            var txtBox = $get(’" + txtID + @"’);
            var count = txtBox.value.length;

            // Update that number in the div
            $get(’CharCount1’).innerHTML = count;
 
            // Change the background color of the textbox
            // according to the length of the string.
            if (count < 5)
                txtBox.style.backgroundColor = ’white’
            else if((count > 4) && (count < 10))
                txtBox.style.backgroundColor = ’yellow’
            else
                txtBox.style.backgroundColor = ’red’
        }

Finally, add the JavaScript to the page.

By using the RegisterClientScriptBlock method, we will add the above JavaScript methods to the page.

    // If you want the <script></script> attached to the above
    // JavaScript code, add the last parameter (true) to the
    // RegisterClientScriptBlock method.
    // If you want to manually add the <script></script> enclosures
    // use the commented method below.
    ClientScript.RegisterClientScriptBlock(this.GetType(), "CountChars", countChars, true);
    //ClientScript.RegisterClientScriptBlock(this.GetType(), "CountChars", countChars);

Generated JavaScript

It’s interesting to see what JavaScript is generated. We can see the generated JavaScript by looking at the source of the page. It’s the two methods we added wrapped around inside the <script> tags.

<script type="text/javascript">
<!--

            // Add the handlers
            function pageLoad()
            {
               $addHandler($get(’txtCharCount1’), ’keyup’, CountChars);
            }

            // Method that counts the characters
            function CountChars()
            {
                // Obtain the length of the string in the textbox.
                var txtBox = $get(’txtCharCount1’);
                var count = txtBox.value.length;

                // Update that number in the div
                $get(’CharCount1’).innerHTML = count;
     
                // Change the background color of the textbox
                // according to the length of the string.
                if (count < 5)
                    txtBox.style.backgroundColor = ’white’
                else if((count > 4) && (count < 10))
                    txtBox.style.backgroundColor = ’yellow’
                else
                    txtBox.style.backgroundColor = ’red’
            }
            // -->
</script>

The MS AJAX piece above

In the above code we are using two shortcuts from the MS AJAX functionality: $addHandler and $get. In order for these shortcuts to be available on the page, don’t forget to add the scriptmanager to the page:

        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>

Enhanced Scenario and Methods

The above set of methods are tied to just one textbox and one div. In this case, let’s generalize the character counting method to take textbox and div as parameters. This way, the same code can be applied to multiple textboxes on a given page.

As you can see from the figure below, here we have two separate textboxes with two separate independently changing counters attached to them.

Figure 1. Character Counting with AJAX

Figure 1. Character Counting with AJAX

The Enhanced User Interface

In this scenario, we have two textboxes and two character counting divs. Following is some sample code for these user interface elements:

<table border="1">
    <tr>
        <td>
            <asp:Label ID="lblCharCount1" runat="server" Text="Char Count1:"></asp:Label>
        </td>
        <td>
            <asp:TextBox ID="txtCharCount1" runat="server"></asp:TextBox>
            <div id="CharCount1">
            </div>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="lblCharCount2" runat="server" Text="Char Count2:"></asp:Label>
        </td>
        <td>
            <asp:TextBox ID="txtCharCount2" runat="server"></asp:TextBox>
            <div id="CharCount2">
            </div>
        </td>
    </tr>
</table>

The Extended set of Character Counting methods

Just as in the previous case, let’s add some JavaScript methods via the asp.net page.

/// <summary>
/// Provides character counting functionality for
/// multiple textboxes on a page.
/// </summary>
private void AddCharCountEx()
{
    // Obtain the unique ids of the textboxes.
    string txtID1 = txtCharCount1.UniqueID;
    string txtID2 = txtCharCount2.UniqueID;

    // Prepare the JavaScript methods for counting characters
    string countChars = @"
        // Add the necessary handlers
        function pageLoad()
        {
           $addHandler($get(’" + txtID1 + @"’), ’keyup’, CountChars1);
           $addHandler($get(’" + txtID2 + @"’), ’keyup’, CountChars2);
        }

        // Call the couting method with proper parameters
        // Background is yellow at 5 chars and red at 10.
        function CountChars1()
        {
            CountChars($get(’" + txtID1 + @"’), $get(’CharCount1’), 5, 10);
        }

        // Call the counting method with proper parameters
        // Background here is yellow at 10 chars and red at 15.
        function CountChars2()
        {
            CountChars($get(’" + txtID2 + @"’), $get(’CharCount2’), 10, 20);
        }

        // Fully parameterized character counting method.
        function CountChars(txtBox, CharCount, bound1, bound2)
        {
            // Get the length and update the count.
            var count = txtBox.value.length;
            CharCount.innerHTML = count;
 
            // Color the background according to the bounds.
            if (count <= bound1)
                txtBox.style.backgroundColor = ’#FFFFFF’
            else if((count > bound1) && (count <= bound2))
                txtBox.style.backgroundColor = ’#FFFF99’
            else
                txtBox.style.backgroundColor = ’#FFA07A’
        }
        ";

    // If you want the <script></script> attached to the above
    // JavaScript code, add the last parameter (true) to the
    // RegisterClientScriptBlock method.
    // If you want to manually add the <script></script> enclosures
    // use the commented method below.
    ClientScript.RegisterClientScriptBlock(this.GetType(), "CountChars", countChars, true);
    //ClientScript.RegisterClientScriptBlock(this.GetType(), "CountChars", countChars);
}

In this case we are adding handlers for the individual textboxes. These handlers call the final CountChars method with the proper objects for textboxes and divs. The bounds (where the yellow, red backgrounds kickin) are also parameterized.

As explained in the figure below, here we have two separate textboxes with two separate independently changing counters attached to them.

Figure 2. Character Counting with AJAX Explained

Figure 2. Character Counting with AJAX Explained
Bookmark and Share This

More Articles With Similar Tags
icon-ajax-to-existing-projects.jpg
Since JavaScript has been supported by every major web browser for a long time now, every decent-sized web site uses some JavaScript. Now that ASP.NET AJAX is available, you might want to refactor and start adding some of the functionality available in these libraries. This article goes through the initial refactoring steps.
icon-ajax-browser-detection.jpg
ASP.NET AJAX client side libraries provide a Sys.Browser class. This class along with objects like Sys.Browser.InternetExplorer can be used to detect the browser that the current page is running on. This article discusses the browser detection from the client side.
icon-ms-ajax-validation.jpg
Since JavaScript is a loosely-typed language, type checking is not done for you automatically. If you are writing library-type functions (those that would be used by other developers), it is very useful to validate the parameters. Here is how MS AJAX does the parameter validation.
icon-extender-class-hierarchy.jpg
This article looks at how a control written with MS AJAX gets initialized on the client side. Discusses the JavaScript methods from the client-side library that get called in the initialization of the control. The example used here is the creation of an instance an autocompleteextender control.
icon-ajax-sys-namespaces.jpg
This article looks at how Microsoft AJAX library adds (‘simulates’) the namespace functionality. Understanding this not only lets you create namespaces in your client-side JavaScript code, but also helps you debug the client-side code effectively.
About  Contact  Privacy Policy  Site Map