.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> Javascript >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Characters Count in a Text Box

Posted By:Lakhan Pal Garg       Posted Date: June 16, 2010    Points: 10    Category: Javascript    URL: http://www.dotnetspark.com  

This java code sample shows how to find the Characters Count in a Text
 

Call to JavaScript Method on Different Event (onkeypress,onkeyup,onkeydown,onPaste) of TextBox

private void AddScriptCounter()
    {        
        txtMessage.Attributes.Add("onkeypress", "CountCharactersGeneral('" + txtMessage.ClientID + 

"','inputTxtMessageCountAge'," + 4000 + ")");
        txtMessage.Attributes.Add("onkeyup", "CountCharactersGeneral('" + txtMessage.ClientID + 
"','inputTxtMessageCountAge'," + 4000 + ")");
        txtMessage.Attributes.Add("onkeydown", "CountCharactersGeneral('" + txtMessage.ClientID + 
"','inputTxtMessageCountAge'," + 4000 + ")");
        txtMessage.Attributes.Add("onPaste", "CountCharactersGeneral('" + txtMessage.ClientID + 
"','inputTxtMessageCountAge'," + 4000 + ")");
    }

Java Script Code
Javascript Method to COunt the Character and Restrict to the maximum charcter that can be entered into a textbox.
sourceTextBox (Source Text Box)
displayControl (Control where you want to diplay remaing characters count)
maxLength (Maximum number of Character that can be entered into the Source Text Box.)

function CountCharactersGeneral(sourceTextBox, displayControl, maxLength)
{

    if(sourceTextBox != null && displayControl != null)
    {
  sourceTextBox = document.getElementById(sourceTextBox);
                displayControl = document.getElementById(displayControl);
                if(sourceTextBox != null)
                {
                    var len = sourceTextBox.value.length
                    if (len<=maxLength) //if entered charcters less than the Maximum Limit.
                    {
                        //Shows Number of characters Remaining 
                        displayControl.innerHTML = maxLength -len + " Character(s) remaining.";
                    }
                    else
                    {
                        sourceTextBox.value = sourceTextBox.value.substring(0, maxLength);
                        return false;
                    }
               }
    }
}

Thanks & Regards
Lakhan Pal Garg


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend