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

拥有回忆 提交于 2021-02-07 18:17:55

问题


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.


回答1:


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 );
});



回答2:


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




回答3:


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




回答4:


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

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



来源:https://stackoverflow.com/questions/9567824/why-does-jquery-change-only-trigger-when-i-leave-the-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!