Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does jQuery.change() only trigger when I leave the element?

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.

like image 627
Weblurk Avatar asked Dec 10 '22 02:12

Weblurk


1 Answers

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 );
});
like image 200
Mild Fuzz Avatar answered Jan 11 '23 23:01

Mild Fuzz