1

Is there is any way to detect text box value changed , whether users changes it explicitly or some java script code modified the text box? I need to detect this change.

Imran Qadir Baksh - Baloch
  • 32,612
  • 68
  • 179
  • 322

1 Answers1

2

To track for user changes you can add a handler for key presses:

$(selector).keypress(function() {
    // your code
});

Update: besides watching for key presses, you can use the change function to watch from changes via JavaScript. It won't work immediatly for user changes (is only called after the input loses focus), but together with the keypress I believe you cover all cases:

$(selector).change(function() {
    // the same code
});

setTimeout(function() { $(selector).val("changed"); }, 2000); // Will trigger the change

Edit: sorry, it seemed to work for JavaScript too, but I was mistaken... This question, however, will be able to solve your problem (tested with setTimeout, and it was able to detect the change).

I posted an example in jsFiddle. With this new watch plugin, you no longer need keypress or change: it will work for key typing, copy/pasting, JavaScript, etc.

Community
  • 1
  • 1
mgibsonbr
  • 21,755
  • 7
  • 70
  • 112
  • @user960567 Have you tried the linked question suggestion? Check my updated answer, I posted an example at jsFiddle. – mgibsonbr Feb 02 '12 at 08:49
  • This is not a good to have timer to check the value changed every time. – Imran Qadir Baksh - Baloch Feb 02 '12 at 09:34
  • @user960567 I agree. However, AFAIK polling is the only solution that will work for JavaScript also (a combination of `keypress` and `change` works for all user scenarios - typing, cut/paste, drag and drop - but not for JavaScript). This, or modifying your scripts so none of them changes the input field without also calling your code... – mgibsonbr Feb 02 '12 at 09:44
  • I am marking your post as answer but it is worth to only fallback to alternative/polyfill if browser does not support the native one. For example, FF natively support watch. Other browser support DOMAttrModified. Check this for improve your version, http://darcyclarke.me/development/detect-attribute-changes-with-jquery/. BTW, Thanks. – Imran Qadir Baksh - Baloch Feb 02 '12 at 11:22