Javascript postback functions

Quick article explaining how to fire your own javascript functions before an asp.net page posts back. It's handy for pre-validation formatting and any number of any other things. I've found that it's handy to set this up the site's master page or a generic base page and a common javascript include so that it's available whenever you need it - there's very little overhead. Some of the code below is a bit ratty as I ripped this out of site in the middle of development. Hopefully in time I'll tidy this up and make it a complete client-side solution but the concept is sound and I've had no problems with it so far.

So, first this bit needs to go into the codebehind of the page. All it does is add an onSubmit event to the standard asp.net form.

System.Web.UI.HtmlControls.HtmlForm frm = (System.Web.UI.HtmlControls.HtmlForm)this.FindControl("form1");
if (frm != null)
{
	frm.Attributes.Add("onSubmit", "newOnSubmit();");
}

Not the most portable thing ever as the form Id is hard-coded, but it'll do for now. Next we need to add some javascript into the common include. This consists of 3 parts, a global array where the callback functions are stored, the new onsubmit function referred to in the code above, and a function to add postback functions into the global array.

Global Array:

var onPostBack = new Array();

New OnSubmit:

function newOnSubmit(eventTarget, eventArgument){
	for(i=0; i < onPostBack.length; i++ ){
		onPostBack[i]();
	};
	return true;
}

Function for adding Postback functions:

function addPostBack(f){
	onPostBack[onPostBack.length] = f;
}

All done! Now any time you need to run some client-side code before posting back to asp.net you can simply add:

function uCasePostcode(){
	var pcode = $('.postcodeField').val();
	$('.postcodeField').val(pcode.toUpperCase());
}

addPostBack(uCasePostcode);	

This website and its content is copyright of NMGLC and respective authors - © NMGLC 2008. All rights reserved.