Trigger Web Forms TextChanged after a JavaScript edit

Assigning an input's JavaScript value does not automatically raise its change event. Dispatch the event after setting the value if an existing Web Forms TextBox should perform its normal AutoPostBack action.

Use the standard browser event API rather than Internet Explorer's obsolete fireEvent. This remains a .NET Framework Web Forms server-control technique.

Wire the page

Place this inside an existing page's server form:

HTML
<asp:TextBox ID="ValueBox" runat="server" AutoPostBack="true"
  OnTextChanged="ValueBox_TextChanged" />
<button type="button" onclick="setValue()">Set example</button>
<asp:Label ID="Result" runat="server" />
<script>
function setValue() {
  const input = document.getElementById('<%= ValueBox.ClientID %>');
  input.value = 'Example';
  input.dispatchEvent(new Event('change', { bubbles: true }));
}
</script>

Add this code-behind handler:

C#
protected void ValueBox_TextChanged(object sender, EventArgs e) {
	Result.Text = Server.HtmlEncode(ValueBox.Text);
}

Open the page and click Set example. The browser posts the changed value and the label displays Example.

Preserve server-side validation

TextChanged is based on a difference between posted values. Setting the same value again may not produce another server change notification. Rebinding the TextBox too early in the lifecycle can overwrite the submitted value.

Keep the field writable when posted edits are intended. Server-side ReadOnly settings can cause posted values to be ignored. Client scripts are not a trust boundary. Validate and authorize the resulting value on the server even when the visible editor is controlled by your own code.

Official references

TextBox.TextChanged Event (System.Web.UI.WebControls)
Occurs when the content of the text box changes between posts to the server.
https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.textbox.textchanged?view=netframework-4.8.1
TextBox.TextChanged
EventTarget: dispatchEvent() method - Web APIs | MDN
The dispatchEvent() method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent().
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
Event dispatch

Author: Herman Schoenfeld