Why does jQuery.change () only start when I exit an element?

I have a textarea element and I want to print the number of characters written above the text box when I type. HTML looks like this:

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

and javascript:

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

But the counter only β€œupdates” when I go outside the text box. Why is this? I want the counter to be updated on the fly, as I write.

+4
source share
4 answers

This is a known behavior of a change event. It does not fire until the element has lost focus. From the docs:

A change event is dispatched to an element when its value changes. This Event is limited to items, boxes, and items. For selection fields, checkboxes, and radio buttons, the event fires immediately when the user makes a choice with the mouse, but for other types of elements the event is delayed until the element loses focus.

Instead, I would associate the script with keyup (you could use other key events, but in this context, it is most appropriate to use up):

 jQuery( "#text" ).keyup(function(){ var numberOfChars = jQuery( "#text" ).val().length; jQuery( "#counter" ).html( numberOfChars ); }); 
+9
source

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

+1
source

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

+1
source

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

Allows you to detect the keyup event, insert data using the mouse ...

+1
source

Source: https://habr.com/ru/post/1399788/


All Articles