6

I have a textarea element and I want to print the number of characters written, above the textarea, as I'm typing. The HTML looks like this:

<p id="counter"></p>
<textarea id="text"></textarea>

and the javascript:

jQuery( "#text" ).change( function(){
    var numberOfChars = jQuery( "#text" ).val().length;
    jQuery( "#counter" ).html( numberOfChars );
});

But the counter only "updates" when I click outside the textarea. Why is that? I want the counter to update on the fly as I'm writing.

Weblurk
  • 6,562
  • 18
  • 64
  • 120
  • Just to note where this behaviour is specified: *The change event occurs when a control loses the input focus and its value has been modified since gaining focus* [w3.org](http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-htmlevents) – lonesomeday Mar 05 '12 at 14:03
  • @lonesomeday Then it makes sense now. Tnx. – Weblurk Mar 05 '12 at 14:05

4 Answers4

11

this is known behaviour of the change event. It does not fire until the element has lost focus. From the docs:

The change event is sent to an element when its value changes. This event is limited to elements, boxes and elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.

I would bind the script to the keyup instead (you could use the other key events, but up makes the most sense in this context):

jQuery( "#text" ).keyup(function(){
    var numberOfChars = jQuery( "#text" ).val().length;
    jQuery( "#counter" ).html( numberOfChars );
});
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
Mild Fuzz
  • 29,463
  • 31
  • 100
  • 148
3

$('input#myId').bind('input', function() {
  //some code
});

It allows to detect keyup event, paste data with the mouse...

Elie Destremau
  • 131
  • 1
  • 4
2

Try using the keyup event instead of change. See it in action: http://jsfiddle.net/ren4A/1/

T. Junghans
  • 11,385
  • 7
  • 52
  • 75
1

try .on('keyup') or .on('keypress') or .on('keydown')

Alexander Corwin
  • 1,097
  • 6
  • 11