问题
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