Skip to content Skip to sidebar Skip to footer

How To Make Onchange Event Happened In Code-behind In Asp.net?

Suppose I have a textbox Mytbx and I have a javascript for its onchange event. I hook it up in code behind in Page_Load event like: Mytbx.Attributes.Add('onchange', 'test();') The

Solution 1:

onchange will only be triggered on client side when you directly type something and leave the textbox. So nothing will happen when you set the textbox value in code behind.

If you want to handle the text change event on client side:

<script>functiontest(txt){
         alert(txt.value);
     };
</script><asp:TextBoxID="txt"runat="server"onchange="test(this);"></asp:TextBox>

If you want to handle text change event on server side, you could do this:

HTML:

<asp:TextBoxID="txt"runat="server"OnTextChanged="txt_OnTextChanged"AutoPostBack="true"></asp:TextBox>

CS:

protectedvoidtxt_OnTextChanged(object sender, EventArgs e)
{
     // Do something
}

Solution 2:

You are mixing client and server processing. If you change the textbox on the SERVER, there is no client code to run yet becuase you haven't posted the form back. If you have javascript code that has to run when you change something on the server, you need to register that Javascript function to run when the page loads when your postback is complete. Check this out: http://msdn.microsoft.com/en-us/library/system.web.ui.page.registerstartupscript(v=vs.110).aspx

Post a Comment for "How To Make Onchange Event Happened In Code-behind In Asp.net?"