【问题标题】:How to limit the size of an HTML textarea with JavaScript?如何使用 JavaScript 限制 HTML 文本区域的大小?
【发布时间】:2009-10-19 12:52:00
【问题描述】:

有人有代码来限制文本字段中的字符并显示字符数吗?

我需要 twitter 状态输入之类的东西,但我在网上找不到任何东西。如果那里没有任何东西,我可能会制作一个 jQuery 插件或至少开源这个东西。

谢谢!

【问题讨论】:

标签: jquery html textarea


【解决方案1】:

看看这个页面:

Interactive character limit for textarea using Jquery

 <script language="javascript">
 function limitChars(textid, limit, infodiv)
 {
     var text = $('#'+textid).val(); 
     var textlength = text.length;
     if(textlength > limit)
     {
         $('#' + infodiv).html('You cannot write more then '+limit+' characters!');
          $('#'+textid).val(text.substr(0,limit));
          return false;
     }
     else
     {
      $('#' + infodiv).html('You have '+ (limit - textlength) +' characters left.');
      return true;
     }
 }
 </script>

然后将该函数绑定到您的 textarea 的 keyup 事件。在 jQuery 的文档就绪事件中这样做:

$(function(){
    $('#comment').keyup(function()
    { 
        limitChars('comment', 20, 'charlimitinfo'); 
    })
});

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-11
  • 2016-10-10
相关资源
最近更新 更多