简体   繁体   English

ASP文本框多行文本计数器

[英]ASP Textbox MultiLine Text Counter

Can anyone simplify my code please, this work on my page, but when I checked on Google Developer tool console, I got this error: 任何人都可以简化我的代码,这可以在我的页面上进行,但是当我在Google Developer工具控制台上检查时,出现了以下错误:

Uncaught TypeError: Cannot read property 'length' of undefined 未捕获的TypeError:无法读取未定义的属性“ length”

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 is with this line: 您的问题是此行:

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

txtCounter is not the client ID of your textarea control when rendered to the client. txtCounter不是呈现给客户端的textarea控件的客户端ID。 View your page source to find the client ID, or use: 查看页面源以找到客户端ID,或使用:

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

Here's my working example using a 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM