Friday, May 20, 2011

Limiting the No. of Characters in TextBox using JQuery

1. In aspx page:
<div>
<div>
<asp:ImageButton ID="imgAddCommentUser" CommandName="AddReply" runat="server" />
<asp:TextBox ID="txtReplies" runat="server" TextMode="MultiLine" onKeyUp="textCounter(this.id);"Text="Write a replies..."></asp:TextBox>
</div>
<div class="clear">
</div>
<div style="float: right; padding: 0 0 0 50px; *margin-top: -15px;"><span id="spanLeftChar" runat="server">
<small>4000 characters left</small>
</span>

In Jquery.js
---------------
eg: 4000 characters


 
        var spanObj = $(txtId).parent().next().next().children("span:first");       

        len = $(txtId).val().length;
        
        if (len > limit)
            $(txtId).val($(txtId).val().substring(0, limit));


      if((limit - len)>=0)
          $(spanObj).html("<small>" + (limit - len) + " characters left </small>")
        else
            $(spanObj).html("<small>0 characters left </small>")
    }

    function textCounter(txtId)
     {            
        var limit = 4000;
        var txtId = "#" + txtId;

No comments:

Post a Comment