Josh
Josh

Reputation: 384

Listen for input value changed by JavaScript without polling

We have a lot of forms on a website we're developing. Some of these forms have functionality that will populate specific fields using JavaScript based on something else the user does. (For example postcode lookup).

For every form, we want to do something when each form field value is modified.

So, we have a form which may have fields values populated by some JavaScript or another somewhere along the way, and we need to know when the field's values have changed.

Currently the only working solution we've come up with is to use 'polling' to periodically check all fields (using setInterval) to see if their value has changed. We're wondering if anyone can come up with a better solution?

(We are using jQuery 1.11.2).

Update: We have found an answer to this question which I have posted below. However, we do not know what the ramifications of redefining an object's default property might be, so we aren't 100% comfortable with that solution yet and continue to search for more ideas.

Upvotes: 1

Views: 356

Answers (1)

Josh
Josh

Reputation: 384

The solution that GracefulLight posted here that Rory put us onto does work.

You can redefine the object's value property, enabling you to do whatever you like when the value property is set.

Object.defineProperty(document.querySelector(".my-object"), "value", {
  set: function(newValue) {
    console.log("Object's value property has changed");

    // do something
    this.style.borderColor = "#228B22";

    // make sure the value is still passed to the input to be output
    return this.defaultValue = newValue;
  }
});

Upvotes: 1

Related Questions