Count characters in textarea

2019-01-02 17:18发布

I want to count characters in a textarea, so I just made:

<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);
     }
};

What's wrong with my piece of code? It does not work! Well, that was a newbie handwriting, need a help.

21条回答
墨雨无痕
2楼-- · 2019-01-02 17:45

this worked fine for me.

$('#customText').on('keyup', function(event) {
   var len = $(this).val().length;
   if (len >= 40) {
      $(this).val($(this).val().substring(0, len-1));
   }
});
查看更多
笑指拈花
3楼-- · 2019-01-02 17:45

A more generic version so you can use the function for more than one field.

<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>
查看更多
闭嘴吧你
4楼-- · 2019-01-02 17:46

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);
    });
});
查看更多
只若初见
5楼-- · 2019-01-02 17:46
<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>

Use the following to skip using else and also skip getting negative count.

查看更多
浪荡孟婆
6楼-- · 2019-01-02 17:49

Here my example. Supper simple

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

查看更多
柔情千种
7楼-- · 2019-01-02 17:51

⚠️ The accepted solution is flawed.

Here are two scenarios where the keyup event will not get fired:

  1. The user drags text into the textarea.
  2. The user copy-paste text in the textarea with a right click (contextual menu).

Use the HTML5 input event instead for a more robust solution:

<textarea maxlength='140'></textarea>

JavaScript (demo):

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

textarea.addEventListener("input", function(){
    var maxlength = this.getAttribute("maxlength");
    var currentLength = this.value.length;

    if( currentLength >= maxlength ){
        console.log("You have reached the maximum number of characters.");
    }else{
        console.log(maxlength - currentLength + " chars left");
    }
});

And if you absolutely want to use jQuery:

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

    if( currentLength >= maxlength ){
        console.log("You have reached the maximum number of characters.");
    }else{
        console.log(maxlength - currentLength + " chars left");
    }
});
查看更多
登录 后发表回答