5

I wrote a jQuery character counter, it works when I type, but not when text is pasted. The function is executed upon paste, but count doesn't change. I am not sure if val() function is correct or really in synch with DOM. Any ideas?

 counter = function () {
     $j("strong#status-field-char-counter").text($j("#Panel1messagesmessage").val().length);
     alert('event');
 };


 $j("textarea").keyup(counter);
 $j("textarea").bind('paste', counter);
 $j("#Panel1messagesmessage").bind('copy', counter);
 $j("#Panel1messagesmessage").bind('delete', counter);
thecodedeveloper.com
  • 3,220
  • 5
  • 36
  • 67
AlexA
  • 4,028
  • 8
  • 51
  • 84
  • 'paste' is not listed as a valid event in http://docs.jquery.com/Events/bind ... also, you can add events as the 2nd param of `bind()` as a string with each event separated by a space `$('#selector').bind('click mouseover', function(){} )` – artlung Nov 02 '09 at 15:48
  • Here's a SO question addressing unsupported events: http://stackoverflow.com/questions/237254/how-do-you-handle-oncut-oncopy-and-onpaste-in-jquery – artlung Nov 02 '09 at 15:52

3 Answers3

7

textarea contents can be changed in a number of ways, instead of trying to catch them all, simply install a routine that checks the content every 0.5 second, like

$(function() {
   window.charCount = 0;
   setInterval(function() {
      var c = $("textarea").val().length;
      if(c != window.charCount) {
        window.charCount = c;
        $("span").html(window.charCount); 
      }
    }, 500);
})
user187291
  • 53,363
  • 19
  • 95
  • 127
3

I usually use keyup in combination with change

The change event fires when the textbox loses focus, but only if the value was modified since it received focus.

Josh Stodola
  • 81,538
  • 47
  • 180
  • 227
  • I did a try with `keydown`, but `keyup` seems to do the trick well, very much for _paste_ as well. – Irf Jan 03 '18 at 07:25
2

Quick play about:

$("#textarea").change(function() {
              $("#status-field-char-counter").text($("#textarea").val().length);
         }).keyup(function() {
          $("#status-field-char-counter").text($("#textarea").val().length);
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<p id="status-field-char-counter">here</p>
    <input id="textarea" type="text" />
Syfer
  • 4,262
  • 3
  • 20
  • 37
S Philp
  • 452
  • 3
  • 14