DEV Community

Alex Blinov
Alex Blinov

Posted on • Originally published at jetrockets.pro

onChange trigger example with React

Recently, I faced the issue. There is a form with some fields. Each field has several functions; functions do something. For example, one function writes the field name and its value into the object. Then the customer asks to add the buttons with specified values. When the button is clicked, the relevant field should update its value.
Here is the trigger hack that calls the onChange function of that field.

function triggerInput(enteredName, enteredValue) {
  const input = document.getElementById(enteredName);

  const lastValue = input.value;
  input.value = enteredValue;
  const event = new Event("input", { bubbles: true });
  const tracker = input._valueTracker;
  if (tracker) {
    tracker.setValue(lastValue);
  }
  input.dispatchEvent(event);
}

Live example link

Top comments (0)