【问题标题】:ASP Textbox MultiLine Text CounterASP 文本框多行文本计数器
【发布时间】:2015-08-31 03:41:27
【问题描述】:

谁能简化我的代码,这在我的页面上工作,但是当我在谷歌开发者工具控制台上检查时,我得到了这个错误:

未捕获的类型错误:无法读取未定义的属性“长度”

以下代码:

  <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>

【问题讨论】:

  • 有直接标签编辑权限的人可以修复这个标签吗?显然不是asp-classic

标签: asp.net textbox


【解决方案1】:

你的问题在于这一行:

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

txtCounter 不是您的 textarea 控件在呈现给客户端时的客户端 ID。查看您的页面源以查找客户端 ID,或使用:

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

这是我使用简单文本区域的工作示例:

<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>

【讨论】:

  • 感谢您的回答,是的,这也有效.. 我仍然遇到相同的未捕获类型错误:无法读取未定义的属性“长度”。 :(
  • 从页面源中确定控件的客户端 ID 应该很容易。我将使用简单的 html textarea 将我的工作示例添加到答案中。我还在使用较旧的 jquery (1.6.4),因此我将您的“on”替换为“bind”-您可能会更幸运……但是,您的问题很可能与您的选择器有关,所以找到 ID 并调整选择器以相应地抓取它。
猜你喜欢
  • 1970-01-01
  • 2011-10-29
  • 2012-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-04
相关资源
最近更新 更多