2

is there a method in jquery that allows to catch when field is modified by script?

This only works when input field modified by hands

$('input[name=myInput]').change(function() { ... });

so as this

$('input[name=myInput]').on('input', function() { ... });

I want an event listener for this field to be able to catch this:

 $('input[name=myInput]').val('changed_value');
AnKing
  • 1,994
  • 6
  • 31
  • 54
  • 8
    `$('input[name=myInput]').val('changed_value').trigger('change');` is the simplest way – A. Wolff Dec 30 '13 at 15:38
  • the change event will be fired only when a user interaction changes the value of an input field, when a script changes the value it is not fired... – Arun P Johny Dec 30 '13 at 15:40
  • Though i can't say it's the most efficient method, 'watching' the `input` field ([as suggested in this answer](http://stackoverflow.com/questions/1948332/detect-all-changes-to-a-input-type-text-immediately-using-jquery)) by using `setInterval()` is a solution – Matt Dec 30 '13 at 15:47
  • If you're programatically changing it, then why would you need a listener? Maybe you're over-thinking this. See very first comment above. – Sparky Dec 30 '13 at 15:55

1 Answers1

1

I would also do as A. Wolff says, which is best way :

$('input[name=myInput]').val('changed_value').trigger('change');

Though, if you really want it to always trigger a change event when you programatically change it (but i don't recommend it !), you could override jQuery val function with something like this :

(function ($) {
  var originalVal = $.fn.val;
  $.fn.val = function(value) {
    if (typeof value != 'undefined') {
        // setter
        originalVal.call(this, value);
        this.trigger('change');
    }else{
        // getter
        return originalVal.call(this, value);
    }
  };
})(jQuery);

Source

Community
  • 1
  • 1
Florian F.
  • 4,700
  • 26
  • 50