About Me

My photo
Northglenn, Colorado, United States
I'm primarily a BI Developer on the Microsoft stack. I do sometimes touch upon other Microsoft stacks ( web development, application development, and sql server development).

Wednesday, July 05, 2006

On change event in ASP.Net

In ASP.Net the ontextchanged event doesn't get called until a postback, the problem we had was to ask the user before leaving the page, if they would like to save any of their changes that were made, and to enable the submit button if there were changes. We had to go to javascript, again, for this answer.

<script language="javascript" type="text/javascript">
window.onbeforeunload = saveChanges;
function saveChanges()
{
var changes = document.getElementById("<%=this.ButtonSubmit.ClientID%>").disabled;
if(!changes)
{
event.returnValue = 'Changes were not saved. Click Cancel to go back and submit changes, or click OK to continue.';
}
}

function enableSubmit()
{
document.getElementById("<%=this.ButtonSubmit.ClientID%>").disabled = false;
}
</script>


The first function: saveChanges() is called when ever the user tries to change the current page or close the browser. It just asks if they user wants to leave without saving.

The second function is called when ever a textbox, or other asp/html control has changed. This basically just enables the submit button.

So, within the page we might have a ASP.Net control like this:

<asp:textbox id="TextBox1" runat="server" onchange="enableSubmit()" width="49px"><asp:textbox>


Now, you would end up getting a warning in ASP.Net since it doesn't recognize the onchange event, since this is actually a javascript event. The trick here is when the page is render this is how it would look in the html:

<input id="ctl00_ContentPlaceHolder1_TextBox1" style="WIDTH: 49px" onchange="enableSubmit()" name="ctl00$ContentPlaceHolder1$TextBoxNotes">

No comments: