3

I have a textarea field and its value is being set programmatically. I would like to know when the value is set and perform further actions after the value has been set. I tried .on("change"), .bind("input propertychange") but nothing seemed to work. Any suggestions?

<textarea id="testField"></textarea>

$("#testField").on("change keyup", function() {
    // your code here
    alert("Changed");
});

Cheers.

Neophile
  • 5,660
  • 14
  • 61
  • 107

1 Answers1

0

It seems that change event is triggered only on direct user interaction with the UI.

Redefining value property that triggers the change event for a specific textarea element worked for me:

// A specific instance of HTMLTextAreaElement
var txt = document.getElementById('txtDescripcion');

// define value property for your input instance
Object.defineProperty(txt, 'value', {
    set: function(newValue) {
        var valueProp = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value');
        var oldValue = valueProp.get.call(txt);
        valueProp.set.call(txt, newValue);

        // Trigger the change event if value changed
        if (oldValue != newValue) {
            txt.dispatchEvent(new InputEvent('change'));
        }
    },
    get: function() {
        var valueProp = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value');
        return valueProp.get.call(txt);
    }
});
cristian.d
  • 135
  • 1
  • 8