129

我想计算文本区域中的字符,所以我做了:

<textarea id="field" onkeyup="countChar(this)"></textarea>

function countChar(val){
     var len = val.value.length;
     if (len >= 500) {
              val.value = val.value.substring(0, 500);
     } else {
              $('#charNum').text(500 - len);
     }
};

我的一段代码有什么问题?这没用!嗯,这是一个新手的笔迹,需要帮助。

4

26 回答 26

184

您在浏览器中看到什么错误?如果您发布的内容不完整,我可以理解为什么您的代码不起作用,但不知道我不能确定。

如果超过限制,您可能应该清除 charNum div,或者写一些东西。

function countChar(val) {
  var len = val.value.length;
  if (len >= 500) {
    val.value = val.value.substring(0, 500);
  } else {
    $('#charNum').text(500 - len);
  }
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<textarea id="field" onkeyup="countChar(this)"></textarea>
<div id="charNum"></div>

于 2011-03-20T20:07:38.087 回答
99

⚠️ 公认的解决方案有缺陷。

keyup以下是事件不会被触发的两种情况:

  1. 用户将文本拖入文本区域。
  2. 用户通过右键单击(上下文菜单)在文本区域中复制粘贴文本。

使用 HTML5input事件来获得更强大的解决方案:

JavaScript(演示):

const textarea = document.querySelector("textarea");

textarea.addEventListener("input", ({ currentTarget: target }) => {
  const maxLength = target.getAttribute("maxlength");
  const currentLength = target.value.length;

  if (currentLength >= maxLength) {
    return console.log("You have reached the maximum number of characters.");
  }

  console.log(`${maxLength - currentLength} chars left`);
});
<textarea maxlength='140'></textarea>

如果你绝对想使用 jQuery:

$('textarea').on("input", function() {
  var maxlength = $(this).attr("maxlength");
  var currentLength = $(this).val().length;

  if (currentLength >= maxlength) {
    return console.log("You have reached the maximum number of characters.");
  }

  console.log(maxlength - currentLength + " chars left");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<textarea maxlength='140'></textarea>

于 2014-12-23T05:18:46.383 回答
87

基于Caterham 函数的改进版本:

$('#field').keyup(function () {
  var max = 500;
  var len = $(this).val().length;
  if (len >= max) {
    $('#charNum').text(' you have reached the limit');
  } else {
    var char = max - len;
    $('#charNum').text(char + ' characters left');
  }
});
于 2012-06-21T06:51:17.500 回答
11

HTML 示例,在我需要计数器的地方使用,注意 textarea 的 ID 和第二个 span 的相关性:id="post"<->id="rem_post"以及包含每个特定 textarea 所需字符数量的 span 的标题

<textarea class="countit" name="post" id="post"></textarea>
<p>
  <span>characters remaining: <span id="rem_post" title="1000"></span></span>
</p>

JavaScript 函数,通常放在</body>我的模板文件之前,需要 jQuery

$(".countit").keyup(function () {
  var cmax = $("#rem_" + $(this).attr("id")).attr("title");

  if ($(this).val().length >= cmax) {
    $(this).val($(this).val().substr(0, cmax));
  }

  $("#rem_" + $(this).attr("id")).text(cmax - $(this).val().length);

});
于 2012-12-12T10:00:37.457 回答
9

这对我来说很好。

$('#customText').on('keyup', function(event) {
   var len = $(this).val().length;
   if (len >= 40) {
      $(this).val($(this).val().substring(0, len-1));
   }
});
于 2013-10-11T14:02:54.473 回答
7

substring()需要成为substr()

示例:jsfiddle.net/xqyWV

于 2011-03-20T20:00:58.650 回答
5

HTML

<form method="post">
<textarea name="postes" id="textAreaPost" placeholder="Write what's you new" maxlength="500"></textarea>

<div id="char_namb" style="padding: 4px; float: right; font-size: 20px; font-family: Cocon; text-align: center;">500 : 0</div>
</form>

jQuery

$(function(){
    $('#textAreaPost').keyup(function(){
      var charsno = $(this).val().length;
      $('#char_namb').html("500 : " + charsno);
    });
});
于 2013-09-13T16:35:19.337 回答
4

好吧,这与我们所说的没有什么不同,但这在所有浏览器中都非常有效。

这个想法是删除任何超出定义长度的文本。

function countTextAreaChar(txtarea, l){
    var len = $(txtarea).val().length;
    if (len > l) $(txtarea).val($(txtarea).val().slice(0, l));
    else $('#charNum').text(l - len);
    }

HTML 代码将是:

<div id="charNum"></div>
<textarea onkeyup="countTextAreaChar(this, 10)" class="textareaclass" id="smallword" rows="40" cols="30" name="smallword"></textarea>
于 2012-11-22T15:49:27.080 回答
3

我做了以上的组合。它允许暂停文本输入,并允许退格,加上保持计数,即使在退格时:

JavaScript 代码:

$(document).ready(function () {

  $('#giftmsg').keypress(function (event) {
    var max = 250;
    var len = $(this).val().length;

    if (event.which < 0x20) {
      // e.which < 0x20, then it's not a printable character
      // e.which === 0 - Not a character
      return; // Do nothing
    }

    if (len >= max) {
      event.preventDefault();
    }

  });

  $('#giftmsg').keyup(function (event) {
    var max = 250;
    var len = $(this).val().length;
    var char = max - len;

    $('#textleft').text(char + ' characters left');

  });

});

HTML:

<div class="col3">
    <h2>3. Optional gift message</h2>
    Enter gift message. Limit 250 characters.<br /><br />
    <textarea cols="36" rows="5" id="giftmsg" ></textarea>
    <a style="padding:7px 0 0 0" href="#">Save Message</a>
    <div id="textleft">250 characters left</div>
</div>

感谢我面前的那些海报!希望这对某人有帮助!

于 2012-11-05T18:58:30.817 回答
3

我为此任务创建了自己的 jQuery 插件,您可以在这里试用:

http://jsfiddle.net/Sk8erPeter/8NF4r/

您可以即时创建字符计数器(以及剩余字符计数器),可以定义是否要剪切文本,可以定义后缀文本,还可以定义短格式及其分隔符。

这是一个示例用法:

$(document).ready(function () {

    $('#first_textfield').characterCounter();

    $('#second_textfield').characterCounter({
        maximumCharacters: 20,
        chopText: true
    });

    $('#third_textfield').characterCounter({
        maximumCharacters: 20,
        shortFormat: true,
        shortFormatSeparator: " / ",
        positionBefore: true,
        chopText: true
    });

    $('#fourth_textfield').characterCounter({
        maximumCharacters: 20,
        characterCounterNeeded: true,
        charactersRemainingNeeded: true,
        chopText: false
    });

    $('#first_textarea').characterCounter({
        maximumCharacters: 50,
        characterCounterNeeded: true,
        charactersRemainingNeeded: false,
        chopText: true
    });

    $('#second_textarea').characterCounter({
        maximumCharacters: 25
    });

});

这是插件的代码:

/**
 * Character counter and limiter plugin for textfield and textarea form elements
 * @author Sk8erPeter
 */ 
(function ($) {
  $.fn.characterCounter = function (params) {
    // merge default and user parameters
    params = $.extend({
      // define maximum characters
      maximumCharacters: 1000,
      // create typed character counter DOM element on the fly
      characterCounterNeeded: true,
      // create remaining character counter DOM element on the fly
      charactersRemainingNeeded: true,
      // chop text to the maximum characters
      chopText: false,
      // place character counter before input or textarea element
      positionBefore: false,
      // class for limit excess
      limitExceededClass: "character-counter-limit-exceeded",
      // suffix text for typed characters
      charactersTypedSuffix: " characters typed",
      // suffix text for remaining characters
      charactersRemainingSuffixText: " characters left",
      // whether to use the short format (e.g. 123/1000)
      shortFormat: false,
      // separator for the short format
      shortFormatSeparator: "/"
    }, params);

    // traverse all nodes
    this.each(function () {
      var $this = $(this),
        $pluginElementsWrapper,
        $characterCounterSpan,
        $charactersRemainingSpan;

      // return if the given element is not a textfield or textarea
      if (!$this.is("input[type=text]") && !$this.is("textarea")) {
        return this;
      }

      // create main parent div
      if (params.characterCounterNeeded || params.charactersRemainingNeeded) {
        // create the character counter element wrapper
        $pluginElementsWrapper = $('<div>', {
          'class': 'character-counter-main-wrapper'
        });

        if (params.positionBefore) {
          $pluginElementsWrapper.insertBefore($this);
        } else {
          $pluginElementsWrapper.insertAfter($this);
        }
      }

      if (params.characterCounterNeeded) {
        $characterCounterSpan = $('<span>', {
          'class': 'counter character-counter',
          'text': 0
        });

        if (params.shortFormat) {
          $characterCounterSpan.appendTo($pluginElementsWrapper);

          var $shortFormatSeparatorSpan = $('<span>', {
            'html': params.shortFormatSeparator
          }).appendTo($pluginElementsWrapper);

        } else {
          // create the character counter element wrapper
          var $characterCounterWrapper = $('<div>', {
            'class': 'character-counter-wrapper',
            'html': params.charactersTypedSuffix
          });

          $characterCounterWrapper.prepend($characterCounterSpan);
          $characterCounterWrapper.appendTo($pluginElementsWrapper);
        }
      }

      if (params.charactersRemainingNeeded) {

        $charactersRemainingSpan = $('<span>', {
          'class': 'counter characters-remaining',
          'text': params.maximumCharacters
        });

        if (params.shortFormat) {
          $charactersRemainingSpan.appendTo($pluginElementsWrapper);
        } else {
          // create the character counter element wrapper
          var $charactersRemainingWrapper = $('<div>', {
            'class': 'characters-remaining-wrapper',
            'html': params.charactersRemainingSuffixText
          });
          $charactersRemainingWrapper.prepend($charactersRemainingSpan);
          $charactersRemainingWrapper.appendTo($pluginElementsWrapper);
        }
      }

      $this.keyup(function () {

        var typedText = $this.val();
        var textLength = typedText.length;
        var charactersRemaining = params.maximumCharacters - textLength;

        // chop the text to the desired length
        if (charactersRemaining < 0 && params.chopText) {
          $this.val(typedText.substr(0, params.maximumCharacters));
          charactersRemaining = 0;
          textLength = params.maximumCharacters;
        }

        if (params.characterCounterNeeded) {
          $characterCounterSpan.text(textLength);
        }

        if (params.charactersRemainingNeeded) {
          $charactersRemainingSpan.text(charactersRemaining);

          if (charactersRemaining <= 0) {
            if (!$charactersRemainingSpan.hasClass(params.limitExceededClass)) {
              $charactersRemainingSpan.addClass(params.limitExceededClass);
            }
          } else {
            $charactersRemainingSpan.removeClass(params.limitExceededClass);
          }
        }
      });

    });

    // allow jQuery chaining
    return this;

  };
})(jQuery);
于 2013-02-09T15:19:07.197 回答
3

我想知道如何做同样的事情,并从这里的每个人那里得到想法,这就是我想出的:

提琴手

<textarea name="message" rows="4" cols="24" maxlength="1000" id="message" placeholder="Message:" style=""></textarea><br/>
<span id="charNum"></span>

$('#message').keyup(function () {
  max = this.getAttribute("maxlength");
  var len = $(this).val().length;
   if (len >= max) {
    $('#charNum').text(' you have reached the limit');
   } else {
    var char = max - len;
    $('#charNum').text(char + ' characters left');
   }
});
于 2017-12-03T00:27:45.723 回答
2
$.fn.extend( {
       limiter: function(limit, elem) {
            $(this).on("keyup focus", function() {
               setCount(this, elem);
           });
            function setCount(src, elem) {
               var chars = src.value.length;
                if (chars > limit) {
                    src.value = src.value.substr(0, limit);
                    chars = limit;
                }
                elem.html( limit - chars );
            }
            setCount($(this)[0], elem);
        }
    });

    var elem = $("#cntr");  
    $("#status_txt").limiter(160, elem);
于 2013-09-30T08:30:03.433 回答
2

似乎最可重用和优雅的解决方案结合了 abive 从 Input 属性中获取 MaxLength ,然后使用可预测的 id 引用 Span 元素......

然后使用,您需要做的就是将 '.countit' 添加到 Input 类,并将 'counter_' + [input-ID] 添加到您的 span

HTML

<textarea class="countit" name="name" maxlength='6' id="post"></textarea>
<span>characters remaining: <span id="counter_name"></span></span>
<br>
<textarea class="countit" name="post" maxlength='20' id="post"></textarea>
<span>characters remaining: <span id="counter_post"></span></span>
<br>
<textarea class="countit" name="desc" maxlength='10' id="desc"></textarea>
<span>characters remaining: <span id="counter_desc"></span></span>

jQuery

$(".countit").keyup(function () {
  var maxlength = $(this).attr("maxlength");
  var currentLength = $(this).val().length;

  if( currentLength >= maxlength ){
    $("#counter_" + $(this).attr("id")).html(currentLength + ' / ' + maxlength);
    }else{
    $("#counter_" + $(this).attr("id")).html(maxlength - currentLength + " chars left");
  }
});
于 2021-02-19T15:24:39.560 回答
0

试试这个。

<textarea maxlength="410" name="about_me" onkeydown="CountLeft(this.form.about_me, this.form.left);" onkeyup="CountLeft(this.form.about_me,this.form.left); "></textarea>

<input maxlength="3" name="left" readonly="" size="3" type="text" value="410" /> characters left

<script>
function CountLeft(field, count) 
{
    var max = "410";
    if (field.value.length > max)
    {
        field.value = field.value.substring(0, max);
    }
    else
    {
        count.value = max - field.value.length;
    }
}
</script>
于 2014-12-12T12:32:31.127 回答
0

更通用的版本,因此您可以将该功能用于多个领域。

<script src="../site/jquery/jquery.min.js" ></script>
<script type="text/javascript">

function countChar(inobj, maxl, outobj) {
    var len = inobj.value.length;
    var msg = ' chr left';
    if (len >= maxl) {
        inobj.value = inobj.value.substring(0, maxl);
        $(outobj).text(0 + msg);
    } else {
        $(outobj).text(maxl - len + msg);
    }
}


$(document).ready(function(){

    //set up summary field character count
    countChar($('#summary').get(0),500, '#summarychrs'); //show inital value on page load
    $('#summary').keyup(function() {
        countChar(this, 500, '#summarychrs'); //set up on keyup event function
    });

});
</script>

<textarea name="summary" id="summary" cols="60" rows="3" ><?php echo $summary ?></textarea> 
<span id="summarychrs">0</span>
于 2015-03-20T01:29:32.723 回答
0
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

    <script>

            function countChar(val) 
            {

             var limit = 1024;

            if ( val.length > limit )
              { 
              $("#comment").val(val.substring(0, limit-1));
              val.length = limit;
              }

              $("#count").html((limit)-(val.length));     
              }

        </script>

        <textarea id="comment" onKeyUp="countChar(this.value)" required></textarea>

        <div id="count"></div>

使用以下内容跳过使用 else 并跳过获取负数。

于 2015-05-19T20:22:34.187 回答
0

这是我的例子。简单的晚餐

$(document).ready(function() {
      
        var textarea    = $("#my_textarea");
  
        textarea.keydown(function(event) {
          
            var numbOfchars = textarea.val();
            var len = numbOfchars.length;
            $(".chars-counter").text(len);

        });
  
  
 }); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="my_textarea" class="uk-textarea" rows="5" name="text"></textarea>
<h1 class="chars-counter">0</h1>

于 2017-01-17T14:00:15.177 回答
0

我们对任何有目的的解决方案都不满意。

所以我们为 JQuery 创建了一个完整的字符计数器解决方案,建立在jquery-jeditable 之上。这是一个textarea插件扩展,可以双向计数,显示自定义消息,限制字符数,还支持jquery-datatables

您可以立即在JSFiddle上对其进行测试。

GitHub链接:https ://github.com/HippotecLTD/realworld_jquery_jeditable_charcount

快速开始

将这些行添加到您的 HTML 中:

<script async src="https://cdn.jsdelivr.net/gh/HippotecLTD/realworld_jquery_jeditable_charcount@1.0.0/dist/jquery.jeditable.charcounter.realworld.min.js"></script>
<script async src="https://cdn.jsdelivr.net/gh/HippotecLTD/realworld_jquery_jeditable_charcount@1.0.0/dist/jquery.charcounter.realworld.min.js"></script>

进而:

$("#myTextArea4").charCounter();
于 2018-10-07T06:04:08.033 回答
0
$(document).ready(function() {
    var count = $("h1").text().length;
    alert(count);
});

此外,您可以放置​​自己的元素 id 或类而不是“h1”,并且长度事件计算文本区域字符串的字符☻</p>

于 2018-10-07T07:28:25.717 回答
0

请记住 Etienne Martin 所说的,您可以使用oninput,因为它会检测到 texarea 内的任何变化。检测您是否复制和粘贴文本。

$('#textarea').on('input', function() {
        var max = 400;
        var len = $(this).val().length;
        var char = max - len;
        if (len >= max) {
            $('#charNum').text(' You have reached the character limit.');
            $('#charNum').addClass("text-danger"); // optional, adding a class using bootstrap
        } else if (char <= 10) {
            $('#charNum').text(char + ' You are reaching the character limit.');
            $('#charNum').addClass("text-warning"); // optional, adding a class using bootstrap
        } else {
            var char = max - len;
            $('#charNum').text(char + ' characters remaining.');
            $('#charNum').addClass("text-success"); // optional, adding a class using bootstrap
        }
        });
于 2021-02-18T06:36:32.557 回答
0

我的方式 :) #summary-field" - 字段,#summary-count - 实时字符计数器

这对于在 TextArea 中跳过输入很有用

function fieldCharactersRestriction(){
    if ($("#summary-field").val().replace(/(\r\n|\n|\r)/gm, "").length <= maxLength){
      summaryCharactersCount = maxLength - $("#summary-field").val().replace(/(\r\n|\n|\r)/gm, "").length;
      $("#summary-count").html(summaryCharactersCount + ' characters left');
    } else {
      $("#summary-field").val($("#summary-field").val().slice(0, -1));
    }
  }

于 2021-11-12T11:02:10.293 回答
0

在这里我做得很紧凑。重新启用任何按钮对我有用

 var x = document.getElementById("password");
 
 x.addEventListener("input" , event =>{
 
      var target = event.currentTarget;
      var maxlength = target.getAttribute("maxlength");
      //current length 
      var clength = target.value.length;
      //checking if length is 10 or not
       if(clength == 10 ){
       //enabling the button
           var btn = document.getElementById("btn");
           btn.disabled = false;
      }
      //printing the current values
      document.getElementById("return") .innerText = clength;
 });
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>replit</title>
   
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
      
    <textarea maxlength="10" id="password"  required  > </textarea> 
    <button id="btn" disabled> submit </button>
      <div id="return"></div>
    <script src="script.js"></script>
  </body>
</html>

于 2021-11-13T10:02:07.863 回答
-1

你的代码有点混乱。这是一个干净的版本:

<script type="text/javascript">
    $(document).ready(function() {
        $("#add").click(function() {
            $.post("SetAndGet.php", {
                know: $("#know").val()
            }, function(data) {
                $("#know_list").html(data);
            });
        });

        function countChar(val) {
            var len = val.value.length;
            if (len >= 500) {
                val.value = val.value.substring(0, 500);
            } else {
                $('#charNum').text(500 - len);
            }
        }
    });
</script>
于 2011-03-20T20:37:48.917 回答
-1
$('#field').keyup(function () {
    var max = 160;
    var len = $(this).val().length;
//  var char = max - len;
    var messages = Math.ceil(len / 160);
    if (len >= max) {
        $('#charNum').text('(' + messages + ') ' + len + '/' + max);
    } else {
        $('#charNum').text(len + '/' + max);
    }
    });
于 2016-03-03T06:59:25.153 回答
-1

如果您使用角度:

<textarea [(ngModel)]="xyz" maxlength="50"></textarea>
{{xyz.length}}/50
于 2022-02-04T20:31:55.167 回答
-2

你可以使用:

    $(document).ready(function () {
  $('#ID').keyup(function () {
   var val = $(this).val();
   len = val.length;
   if (len >= 140) {
    $(this).text(val.substring(0, 140));
   } else {
    console.log(140 - len);
    $('#charNum').empty().append(140 - len);
   }
  });
 });
于 2016-07-22T12:28:25.423 回答