6

Is there a way to bind the change event for a text field in jQuery? I.E. whenever the value changes, call some function? I am currently using keyup but that doesn't hit every case, i.e. right click and paste.

Thanks.

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Justin
  • 42,716
  • 77
  • 201
  • 296
  • http://stackoverflow.com/questions/2823733/textarea-onchange-detection – Shomz Nov 14 '11 at 02:27
  • possible duplicate of [Detect all changes to a (immediately) using JQuery](http://stackoverflow.com/questions/1948332/detect-all-changes-to-a-input-type-text-immediately-using-jquery) – Felix Kling Nov 14 '11 at 02:28

3 Answers3

11
$("#element").bind("keyup input paste", function() {
    //Do Work Here
});
Justin
  • 42,716
  • 77
  • 201
  • 296
  • This is nice, but what's the difference in outcome if you don't `bind` to `paste`? (I see how `keyup` makes sense for older browsers.) – fncomp Nov 15 '11 at 05:39
  • Just for the record. I wanted to validate a text field every time its value changes. `keyup` doesn't works as expected, because if the user type CTRL+V, the event was called twice. Now I'm using only `bind("input", function() {`. Thanks! – thicolares Feb 20 '13 at 19:10
2

Have you tried using the change() trigger?

$('.target').change(function() {
  alert('Handler for .change() called.');
});

http://api.jquery.com/change/

griegs
  • 22,624
  • 33
  • 128
  • 205
  • 2
    .change() only appears to be triggered when losing focus (blur), at least in Chrome. – gak Mar 23 '12 at 00:46
2

keyup seems to work for me with copy and paste, at least in Firefox. Where do you see the problem? Which browser? Can you post an example?

http://jsfiddle.net/9fJwC/

dnuttle
  • 3,810
  • 2
  • 19
  • 19
  • Yeah copy some text, then click into the field, right click and paste. Notice the text is NOT updated. – Justin Nov 14 '11 at 02:45
  • OK I see what you mean. I can hit Ctrl-V to paste and it works, but right-click and Paste doesn't. Even when the input loses the focus. That's some strange behavior. – dnuttle Nov 14 '11 at 11:50