2

I need to fire an event if the input text has changed through Javascript using .val(), from jQuery API (https://api.jquery.com/change/): Note: Changing the value of an input element using JavaScript, using .val() for example, won't fire the event.

Have tried this How can I trigger an onchange event manually? but doesn't seem to work...

This is my code:

<input type="text" id="datePrint" maxlength="10" size="6" disabled>
<img src="scripts/calendar/calendar.png" id="datePick" border="0" align="absmiddle" alt="Pick Date" width="40px" height="40px">

JS: need to activate calendar events

Calendar.setup({inputField:'datePrint',ifFormat:'%d/%m/%Y',button:'datePick',align:'T1',singleClick:true}); 

And this is the calendar JS:

http://www.mediafire.com/view/yfrls2nx4m6ls52/calendarJs.txt

3

2 Answers 2

0

You can always trigger the change event while changing the input value.

$("input#id").trigger('change');
3
  • cant do the trigger because the generated input text comes from a calendar JS.
    – Alpha2k
    Mar 26, 2015 at 12:13
  • Then the calendar JS has to have an API which helps you track when a text is placed in the input field. You can trigger the change there itself. Can you post your code?
    – ArinCool
    Mar 26, 2015 at 12:17
  • code posted... Its pretty hard for me to read the calendar js code, I dont have much time :S
    – Alpha2k
    Mar 26, 2015 at 12:28
0

There are two ways. The simple answer is remember that every-time you use .val() to also call .change().

However, this begs the question on whether the DOM is the best place to keep state information. A more complex but flexible solution is to create a model/view object to store state and let it manage the events and updates.

However, upon further inspection on the comments the actual problem your attempting to address is not how to trigger change events but how to tell when an input has changed when another third party lib has pragmatically changed it.

The first step is to investigate the library in question and see if they provide a change event you can attach to. If not (after considering a different better behaved library), you are probably stuck with a polling solution.

function InputChangePoller(selector) {
  this.el = $(selector);
  this._lastKnownValue = this.el.val();
}

InputChangePoller.prototype.start = function() {
  this._timmer = setImmediate($.proxy(this, 'checkValue'), 10);
  return this;
};

InputChangePoller.prototype.stop = function() {
  clearImmediate(this._timmer);
  return this;
};

InputChangePoller.prototype.checkValue = function() {
  var value = this.el.val();
  if (value !== this._lastKnownValue) {
    this._lastKnownValue = value;
    this.el.trigger('change', value);
  }
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.