Monday 24 February 2014

Count Number of Character in Multiline Textbox - Part I


Count Number of Character in Multiline Textbox - Part I


Hi Guys Today I am going to show you how to count Number of Character in a Multiline textbox and how to restrict the entry after the limit is reached..

Note: It works well with Chrome and IE but doesnt work with Firefox.

Design Part:


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

<!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>Count Number of Character Multiline Textbox I</title>

    <script language = "Javascript">

        function tbLimit() {
            var tbObj = (typeof event.target != 'undefined') ? event.target : event.srcElement;

            if (tbObj.value.length == tbObj.maxLength * 1) return false;

        }
        function tbCount(visCnt) {

            var tbObj = event.srcElement;
            if (tbObj.value.length > tbObj.maxLength * 1) tbObj.value = tbObj.value.substring(0, tbObj.maxLength * 1);

            if (visCnt) visCnt.innerText = tbObj.maxLength - tbObj.value.length;

        }
</script>
</head>
<body>

<form id="form1" runat="server">

<div>
<asp:TextBox ID="TextBox1" runat="server" Columns="30" Rows="10" TextMode="MultiLine" ></asp:TextBox>
<br />
<asp:Label ID="Label1" runat="server"></asp:Label></div>
 
</form>

</body>
</html>

Code-Behind:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        TextBox1.Attributes.Add("onkeypress", "return tbLimit();");
        TextBox1.Attributes.Add("onkeyup", "return tbCount(" + Label1.ClientID + ");");
        TextBox1.Attributes.Add("maxLength", "500");
    }
}

No comments:

Post a Comment

Thank You for Your Comments. We will get back to you soon.

back to top