How to add Characters left feature for Multi line Textbox in Asp.net using Javascript


Write the following design code in default.aspx source file
<asp:Label ID="lbdesc" runat="server" Text="Description"></asp:Label>

<asp:TextBox ID="txtDescription" runat="server" TextMode="MultiLine"  Width="220px" Onkeydown="checkTextAreaMaxLength(this,event,'2000')" ></asp:TextBox>

<asp:Label ID="lbdesccharleft" runat="server" Text="Characters Left "></asp:Label>

<asp:TextBox ID="txtdesccharleft"  runat="server" Width="50px" ReadOnly="True"
 Text=" 2000"> </asp:TextBox>


Write the following script functions in javascript <script> tag:
<script language="javascript" type="text/javascript">

  function chkcharleft(e,t1, t2,val) {
        e.returnValue = false;
       
        document.getElementById(t2).maxlength = val;
        var val1 = document.getElementById(t1).value.length;
       
        if (val - val1 <= 0)
            e.returnValue = false;
        document.getElementById(t2).value = val - val1;
      
    }
   

    function charsleft(t1, t2) {

        document.getElementById(t2).maxlength = val;
        var val1 = document.getElementById(t1).value.length;
        if (val - val1 <= 0)
            e.returnValue = false;
        document.getElementById(t2).value = val - val1;

    }

   function checkTextAreaMaxLength(textBox, e, length)
    {         
    var mLen = textBox["MaxLength"];        
    if(null==mLen)            
    mLen=length;         
    var maxLength = parseInt(mLen);        
    if(!checkSpecialKeys(e))        
    {         
    if(textBox.value.length > maxLength-1)         
    {            
    if(window.event)//IE              
    e.returnValue = false;
    else//Firefox                
        e.preventDefault();
}
}
}

function pageLoad(sender, args) {

        if (args.get_isPartialLoad()) {

document.getElementById('<%= txtdesccharleft.ClientID %>').value = document.getElementById('<%= txtdesccharleft.ClientID %>').value - document.getElementById('<%= txtDescription.ClientID %>').value.length;
}}
</script>

Write the following code in default.aspx.cs page load
protected void Page_Load(object sender, EventArgs e)
    {
      txtDescription.Attributes.Add("onkeyup", "chkcharleft(event, '" + txtDescription.ClientID + "','" + txtdesccharleft.ClientID + "', 2000)");
}

1 comment:

  1. i got an error like this "jscript runtime error 'checkspecialkeys' is undefined" while i entering the text into the text box.Any Suggestions

    ReplyDelete