135

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.

Filburt
  • 17,626
  • 12
  • 64
  • 115
Kyle
  • 1,385
  • 2
  • 9
  • 8
  • In the future, please edit your question or use the comment feature under answers to add additional information or clarification. Answers should be posts that directly solve your problem. If you post a solution to your own problem, accept your solution as the correct answer. I've removed a lot of your 'answers', as you've accepted another. – Tim Post Mar 21 '11 at 03:27
  • [JQuery Character Limit Counter](http://www.jquery2dotnet.com/2014/11/jquery-character-limit-counter.html) – Sender Nov 14 '14 at 03:17

26 Answers26

191

What errors are you seeing in the browser? I can understand why your code doesn't work if what you posted was incomplete, but without knowing that I can't know for sure.

You should probably clear the charNum div, or write something, if they are over the limit.

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Caterham
  • 2,301
  • 1
  • 13
  • 8
  • 1
    really? I have just a span instead of div for id='charNum', let me see again! – Kyle Mar 20 '11 at 20:11
  • After seeing your complete code, what were you expecting it to do differently? What is "broken" about it? – Caterham Mar 20 '11 at 20:14
  • you can remove the "else", just cause we hit 500 doesn't mean that we should prevent #charNum to display the value, the "else" will make the number stop at 1 instead of 0 as it is right now. – Joakim Mar 20 '11 at 20:22
  • @Joakim, I removed the else but, in this case, I'll be getting negative nums! – Kyle Mar 20 '11 at 20:31
  • Maybe just add something to the if, setting charNum to say "You've reached the limit", or something like that. – Caterham Mar 20 '11 at 20:40
  • @Joakim, what do u propose to fix that, namely, to get the 0 and not -1, u can try it out and see that if we clean else then we'll get -1. – Kyle Mar 20 '11 at 20:40
  • @Kyle, Only reason you would be getting a negative number is if you enable the user to input more chars than the max value specified, which you prevent by using substr(0, 500). Edit: Look at the comment in NeXXeuS answer, open jsfiddle and you'll see what I'm talking about. – Joakim Mar 20 '11 at 20:48
  • @Joakim, I did as said, but when I paste word from outside at last of textarea (after end of char number), I get -5, -1, .., but I solved that with a lil trick, here is my last code: function countChar(val,msg,x){ var len = val.value.length; if($(msg).val() == 0) $(msg).html("Enough"); if (len >= x) { val.value = val.value.substr(0, x); }else { $(msg).text(x - len); } }; – Kyle Mar 20 '11 at 21:30
  • @Caterham Congrats man, you are the first that Post the complete answer, all the rest post partial answer. Thanks, very useful! – devasia2112 Jun 28 '13 at 03:24
  • This also won't work if the user pastes content into the field as that will not trigger a keyup event. It should listen for the change event in addition to keyup. – Mark Murphy Feb 05 '15 at 19:07
  • Recently a lightweight jquery plugin has been released You could take a look at https://github.com/Ramon1976/textareacounter – aKiRa Apr 13 '18 at 16:09
  • The solution from @Etienne Martin is better. – nivs1978 Jan 22 '19 at 09:08
  • Don't use this. This solution is flawed as pointed out by Etienne Martin. – Fabian Bigler Mar 01 '19 at 09:32
111

⚠️ 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:

JavaScript (demo):

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>

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) {
    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>
Etienne Martin
  • 10,018
  • 3
  • 35
  • 47
89

Improved version based on Caterham's function:

$('#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');
  }
});
Community
  • 1
  • 1
keithics
  • 8,576
  • 2
  • 48
  • 35
10

HTML sample, used wherever I need a counter, notice the relevance of IDs of textarea and second span : id="post" <-> id="rem_post" and the title of the span that holds the desired characters amount of each particular textarea

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

JavaScript function, usually placed before </body> in my template file, requires 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);

});
Sk8erPeter
  • 6,899
  • 9
  • 48
  • 67
humugus
  • 101
  • 1
  • 3
10

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));
   }
});
johnluttig
  • 750
  • 1
  • 9
  • 24
fatsouls32
  • 109
  • 1
  • 4
7

substring() needs to become substr().

Example: jsfiddle.net/xqyWV

mattsven
  • 22,305
  • 11
  • 68
  • 104
  • @MattCurtis: you should rather post your jsFiddle-demo in the original post (to get more upvotes and) to make it more markable. I tried to edit your post and paste the link, but my edit was rejected. – Sk8erPeter Jan 12 '13 at 19:42
  • Could you please post the FULL sample.. include jquery version that you has used. The sample above is useless. Sorry!. – devasia2112 Jun 28 '13 at 03:21
  • @B4NZ41 Works fine for me. There are also other answers for this that address it better. – mattsven Jun 28 '13 at 15:16
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);
    });
});
Elkingphp
  • 51
  • 1
  • 1
4

I did a combination of the above. It allows for the halting of the text entry, and allows for the backspacing, plus keeps the count, even when backspacing:

JavaScript code:

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

Credit to those posters before me!! Hope this helps someone!

Sk8erPeter
  • 6,899
  • 9
  • 48
  • 67
DJH
  • 82
  • 7
4

Well, this is not that different from what have been said, but this works very well in all browsers.

The idea is to delete any text which overflows the defined length.

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

The HTMl code would be:

<div id="charNum"></div>
<textarea onkeyup="countTextAreaChar(this, 10)" class="textareaclass" id="smallword" rows="40" cols="30" name="smallword"></textarea>
Youssef
  • 2,866
  • 1
  • 24
  • 20
3

I created my own jQuery plugin for this task, you can try it out here:

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

You can create character counters on-the-fly (and also remaining character counters), you can define whether you want to chop text, you can define the suffix texts and you can also define a short format and its separator.

Here's an example usage:

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

});

Here's the code of the plugin:

/**
 * 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);
Sk8erPeter
  • 6,899
  • 9
  • 48
  • 67
3

I was wondering how to do this same thing and taking ideas from everyone here this is what I came up with:

JsFiddle

<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');
   }
});
bckelley
  • 59
  • 1
  • 11
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);
Saurabh Chandra Patel
  • 12,712
  • 6
  • 88
  • 78
2

Seems like the most reusable and elegant solution combines the abive to take MaxLength from the Input attribute and then reference the Span element with a predictable id....

Then to use, all you need to do is add '.countit' to the Input class and 'counter_' + [input-ID] to your 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");
  }
});
Ben Holmes
  • 73
  • 7
0

Try this one.

<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>
Taryn
  • 242,637
  • 56
  • 362
  • 405
Hardik
  • 1,283
  • 14
  • 34
0

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>
Lumis
  • 21,517
  • 8
  • 63
  • 67
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>

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

Shiva Charan
  • 307
  • 3
  • 4
0

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

We weren't happy with any of the purposed solutions.

So we've created a complete char counter solution for JQuery, built on top of jquery-jeditable. It's a textarea plugin extension that can count to both ways, displays a custom message, limits char count and also supports jquery-datatables.

You can test it right away on JSFiddle.

GitHub link: https://github.com/HippotecLTD/realworld_jquery_jeditable_charcount

Quick start

Add these lines to your 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>

And then:

$("#myTextArea4").charCounter();
Vaiden
  • 15,728
  • 7
  • 61
  • 91
0
$(document).ready(function() {
    var count = $("h1").text().length;
    alert(count);
});

Also, you can put your own element id or class instead of "h1" and length event count your characters of text area string ☻

Parham R.
  • 9
  • 3
0

Keeping in mind what Etienne Martin says, you can use oninput, as it detects any change within texarea. Detect if you copy and paste text.

$('#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
        }
        });
0

My way :) #summary-field" - field, #summary-count - live character counter

This is good for skiping enters in 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));
    }
  }

0

HERE i made it quite compact . it worked for me to re-enable any button

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

Your code was a bit mixed up. Here is a clean version:

<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>
Sylvain Guillopé
  • 1,358
  • 9
  • 21
  • Sly, believe me, that does not work, it seems that function that begins with .. function() { .. need to be out of $(document).ready(function() { – Kyle Mar 20 '11 at 20:48
-1

If you are using angular:

<textarea [(ngModel)]="xyz" maxlength="50"></textarea>
{{xyz.length}}/50
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
-2

U can use :

    $(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);
   }
  });
 });
demenvil
  • 1,089
  • 1
  • 12
  • 25