October 28, 2021 at 10:01 am | Programming, web.

A problem I ran into recently is that updating an input value is a form using javascript or jQuery is fairly easy but sometimes this programmatic update of the field does not trigger an onChange event that another piece of code is listening for. Adding a dispatchEvent on the selector can accomplish this.

<script>
  // Get the selector
  const $emailField = document.getElementById('Email');
  // Update the selector value
  $emailField.value = "[email protected]";
  // Trigger a dispatchEvent on the selector
  $emailField.dispatchEvent(new Event("input", { bubbles: true }));
</script>