Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - char counter doesn't work with paste event

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);
like image 341
AlexA Avatar asked Nov 02 '09 13:11

AlexA


2 Answers

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);
})
like image 137
user187291 Avatar answered Nov 03 '22 19:11

user187291


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.

like image 30
Josh Stodola Avatar answered Nov 03 '22 20:11

Josh Stodola