1

I have some code basically like the following

.on("keyup", "input", function (e) {
    this.value = utils.formatNumber(this.value);                    
})
.on("change", "input", function(e) {
    expensiveFunctionThatUpdatesView();
})

As it is, the values are formatted correctly as the user types, but the when the user tabs or clicks its way out of the input field, the onChange event is not triggered (hence the view is not updated). If I comment out the body of the keyup event handler function everything works as intended (except formatting). Why is this so?

AFAIK, there are two conditions that need to be satisfied for an onchange event to be triggered:

  1. One must have entered the control/input field by something that has triggered an onfocus event (storing the old value).
  2. The value that was present on focus is different from the one that exists on "exit"/blur

BTW, I tried changing the code to "blur", but that is not triggered either if I format the field. Using Chrome when testing this.

oligofren
  • 20,744
  • 16
  • 93
  • 180
  • http://stackoverflow.com/questions/2247386/jquery-textbox-valxxxx-not-causing-change-to-fire, http://stackoverflow.com/questions/4672505/why-does-the-jquery-change-event-not-trigger-when-i-set-the-value-of-a-select-us – jbabey Oct 23 '12 at 13:26

2 Answers2

1

Setting a textbox value through javascript (or jQuery via val()/text()) will never trigger a browser change event. You need to save the original value, compare it to the post-format value, and trigger a change programatically:

.on("keyup", "input", function (e) {
    var originalValue = this.value;
    var newValue = utils.formatNumber(originalValue);

    this.value = newValue;

    if (originalValue !== newValue) {
        $(this).trigger('change');
    }
})
jbabey
  • 45,965
  • 12
  • 71
  • 94
  • But in a way, the user _has_ triggered a browser event by inputting text (before it is being formatted). I guess this case is up to the browser implementation to decide on - Firefox actually triggers the change(), whereas WebKit does not. – oligofren Oct 24 '12 at 10:31
0

You could trigger the same callback function for both events to enable the number formatting:

.on( 'keyup change', 'input', function ( e ) {
    this.value = utils.formatNumber( this.value );
    updateView();
})
feeela
  • 29,399
  • 7
  • 59
  • 71
  • No, that would trigger way too many calls for updateView(). updateView() is an expensive function that triggers a lot of serverside activity. will update with this info. – oligofren Oct 23 '12 at 13:09
  • And I am interested in the why's, not the how's :-) – oligofren Oct 23 '12 at 13:11
  • @oligofren I would guess the "why's" are jQuery internals. Have tried to ask that question on [their forums](http://forum.jquery.com/)? – feeela Oct 23 '12 at 13:23