Thursday 6 June 2013

working How to count character of TextBox in ASP.NET

How to count character of TextBox in ASP.NET

 

Here, we will see how to check number of character has been inserted in the TextBox. A TextBox Which has max length 120 character and we insert a character in TextBox max length will be display 119 characters. When We enter 120 characters in the TextBox that will be the Max length. 
Drag and drop a TextBox on the page. Select TextBox and press F4 to property window.
TextMode="MultiLine"
Now add the following code in the Head section of the .aspx page.
<head runat="server">
    <title></title>
    <style type="text/css">
        .valid
        {
            background-color: #FFFFFF;
            color: #000000;
        }     
        .invalid
        {
            background-color: #FFCCCC;
            color: #ff0000;
        }
    </style>
 
    <script language="javascript">
        function textCounter1(field, maxlimit) {
            if (field.value.length > maxlimit) {
                field.value = field.value.substring(0, maxlimit);
                document.getElementById('message').className = "invalid";
                document.getElementById('message').focus();
                //alert('You have reached your maximum character limit.');
            }
            else {
                document.getElementById('message').className = "valid";
            }
          
        }
            function textCounter(field, countfield, maxlimit) {
                if (field.value.length > maxlimit) // if too long...trim it!
                    field.value = field.value.substring(0, maxlimit);
                else
                    countfield.value = maxlimit - field.value.length;
            }
    </script>
</head>
 
Now add the following code in the body section.
  
<body bgcolor="#FFFFFF">
<form name="blah" action="" method="post" runat="server">
    &nbsp;<asp:TextBox ID="message" runat="server" name="message" onkeydown="textCounter(this.form.message,this.form.remLen,120)"
        onkeyup="textCounter1(this.form.message, 120)" class="validentry"
        Height="101px" TextMode="MultiLine" Width="228px"></asp:TextBox>
    <br />
    <input readonly type="text" name="remLen" size="3" maxlength="3" value="120"
    position: absolute; style="width: 34px">Character left<br />
    <br />
    <br />
    </form>
</body>
Now run the application and check number of character has been inserted in the TextBox.
text1.gif
Figure1
Now Insert max length characters in TextBox.
text2.gif
Figure2
 

No comments:

Post a Comment