0

I need an event handler which fires when the value of an input field changes. No matter if the value is changed by the "user" or by "code". This listeners do work, if value changed by user, but not if it is changed by code.

$('#myInput').on('change paste input', function() {  })

My specific problem is that an javascript calendar plugin changes the value of my input field. The "input" event is than not fired because the change is made by code.

Thanks for help.

OOPDeveloper89
  • 207
  • 5
  • 18
  • Changing the value programmatically does not trigger an event, so that's not possible. – Felix Kling Dec 24 '14 at 18:01
  • One possible (untested) solution would be to assign `setter` functionality to your input's `.value` property, but it's a little complicated, and will require a special `onpropertychange` event for old IE. – six fingered man Dec 24 '14 at 18:10
  • Are you sure the plugin doesn't include an event that you can hook into? What's the plugin's website? – six fingered man Dec 24 '14 at 18:10

2 Answers2

1

You can use .trigger('change') to manually trigger an event computationally without user interaction. That means you might have to modify the source code of the plugin, or speak to the plugin author(s) about including this (rather basic) feature.

Ideally, plugins that make changes to the DOM, or manipulate values in the document, should trigger an event (be it the common event handlers recognized by jQuery, or custom events) so that other users can "latch" on to it, for extensibility purposes.

Here is a proof-of-concept fiddle: http://jsfiddle.net/teddyrised/p999rscy/

$(function() {
    $('input').on('change paste input', function() {
        $('body').append('<p>Input value changed.</p>');
    });

    $('button').click(function() {
        $('input').val('New value from button').trigger('change');
    });
});
Terry
  • 63,248
  • 15
  • 96
  • 118
-1

Since the plugin is changing the html of the input element dynamically you can try using the following code:

$(document).on("change paste input","#myInput", function() {//begin event

    //todo: fill with code

  });//end event
Larry Lane
  • 2,141
  • 1
  • 12
  • 18