JQuery - char counter not working with insert

I wrote a jQuery character count, it works when I print, but not when pasting text. The function is executed upon insertion, but the counter does not change. I'm not sure if the function is val()true or really synchronized with the 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);
+5
source share
3 answers

The contents of textarea can be modified in several ways, instead of trying to catch them, just install a procedure that checks the contents every 0.5 seconds, for example

$(function() {
   window.charCount = 0;
   setInterval(function() {
      var c = $("textarea").val().length;
      if(c != window.charCount) {
        window.charCount = c;
        $("span").html(window.charCount); 
      }
    }, 500);
})
+7
source

I usually use keyupin combination withchange

change , , .

+3

Quick game:

 $("#textarea").change(function() {
          $("#status-field-char-counter").text($("#textarea").val().length);
     }).keyup(function() {
      $("#status-field-char-counter").text($("#textarea").val().length);
    });

HTML

 <p id="status-field-char-counter">here</p>
<input id="textarea" type="text" />
+2
source