asp.net - ASP Textbox MultiLine Text Counter -


can simplify code please, work on page, when checked on google developer tool console, got error:

uncaught typeerror: cannot read property 'length' of undefined

below code:

  <asp:textbox id="txtcounter" runat="server" width="250px" textmode="multiline"></asp:textbox>  <span id="chars"></span>     <script>         $(document).ready(function () {         var char2 = ($(this).find('textarea[id$=txtcounter]').val().length);          if (char2 == 0) {          $('#chars').text("100 maximum characters"); }          else {            $('#chars').text( char2 + " characters remaining"); }            textchar();           });          function textchar() {         $('textarea[id$=txtcounter]').on('keyup keydown change',          function (){         var limit = 100;         var lengthtxt = $(this).val().length;         if (lengthtxt >= limit)           { this.value = this.value.substring(0, limit); lengthtxt = limit; }          $('#chars').text((limit - lengthtxt) + " characters remaining")         });         };         </script> 

you problem line:

$('textarea[id$=txtcounter]').on('keyup keydown change', 

txtcounter not client id of textarea control when rendered client. view page source find client id, or use:

$('textarea[id$=<%= txtcounter.clientid %>]').on('keyup keydown change', 

here's working example using simple textarea:

<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">   <script src="./jquery-1.6.4.min.js" type="text/javascript"></script> </head>  <textarea id="txtcounter" width="250px"></textarea> <span id="chars"></span>    <script language="javascript" type="text/javascript">   $(document).ready(function () {     var char2 = ($(this).find('textarea[id$=txtcounter]').val().length);     if (char2 == 0) {        $('#chars').text("100 maximum characters");      }     else {         $('#chars').text( char2 + " characters remaining");     }      textchar();   });    function textchar() {     $('textarea[id$=txtcounter]').bind('keyup keydown change', function (){        var limit = 100;        var lengthtxt = $(this).val().length;        if (lengthtxt >= limit){            this.value = this.value.substring(0, limit);             lengthtxt = limit;         }         $('#chars').text((limit - lengthtxt) + " characters remaining");     });    } </script>         </html> 

Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -