最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why does jQuery.change() only trigger when I leave the element? - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Mar 5, 2012 at 13:55 WeblurkWeblurk 6,81218 gold badges72 silver badges127 bronze badges 2
  • 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 – lonesomeday Commented Mar 5, 2012 at 14:03
  • @lonesomeday Then it makes sense now. Tnx. – Weblurk Commented Mar 5, 2012 at 14:05
Add a comment  | 

4 Answers 4

Reset to default 12

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

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

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

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

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

发布评论

评论列表(0)

  1. 暂无评论