May 24, 2011

Character Counting from Asp.Net Textbox using JavaScript

Many peoples asked on different forums inc that how can we calculate Textbox character onkeyup events using JavaScript. The way is very simple here is short code of that query. I also functionality that if length of character less than or equal to 160 then total no. of sms is 1 and vice versa.
ASPX MARKUP
<div>
    <p>
        Asp.Net TextBox Character Counting using Javascript If > 160 then Show SMS: 02
    </p>
    <asp:TextBox ID="txtMessageText" runat="server" TextMode="MultiLine" onKeyUp="CountCharacter();"></asp:TextBox>
    <asp:RequiredFieldValidator ID="rfvMessageText" runat="server" ErrorMessage="*" ControlToValidate="txtMessageText"
        Display="Dynamic"></asp:RequiredFieldValidator>
    <font size="1">
        <asp:Label ID="lblCountDown" runat="server"></asp:Label>
    </font>
</div>
JAVASCRIPT CODE
function CountCharacter() {
    var count = 0;
    var mgsLength = 0;

    var textField = 
        document.getElementById("<%=txtMessageText.ClientID %>");
    var labelField = 
        document.getElementById("<%=lblCountDown.ClientID %>");

    var length = textField.value.length;
    var setValue = count + length;

    if (setValue == 0) {
        mgsLength = 0;
        labelField.innerHTML = 
            "Total characters " + setValue + "; No of SMS: " + mgsLength;
    }
    else {
        if (setValue <= 160) {
            mgsLength = 1;
            labelField.innerHTML = 
                 "Total characters " + setValue + "; No of SMS: " + mgsLength;
    }
    else {
        var roundLength = setValue / 160;
        mgsLength = Math.ceil(roundLength);
        labelField.innerHTML = 
                 "Total characters " + setValue + "; No of SMS: " + mgsLength;
    }
  }
}