I\'m trying to handle the submit
event of a form
element using jQuery.
$(\"form\").bind(\"submit\", function() {
alert
Yeah, this is annoying. I replace __doPostBack
with my own so that I could get submit events to fire.
Iirc, this is an issue when submitting a form via javascript (which calls to __doPostBack
do) in IE (maybe other browsers too).
My __doPostBack
replacement calls $(theForm).submit()
after replicating the default behavior (stuffing values in hidden inputs)
If you are using .NET Framework 3.5 or up, you can use ScriptManager.RegisterOnSubmitStatement() in your server-side code. The registered script will get called both on normal submit and on DoPostback.
ScriptManager.RegisterOnSubmitStatement(this, this.GetType(), "myKey", "SomeClientSideFunction();");
This works for capturing the submit:
$("form input[type=submit]").live("click", function(ev) {
ev.preventDefault();
console.log("Form submittion triggered");
});
Thanks, @Ken Browning and @russau for pointing me in the direction of hijacking __doPostBack. I've seen a couple of different approaches to this:
The first two seem undesirable for a couple of reasons (for example, suppose in the future someone else needs to add their own functionality to __doPostBack) so I've gone with #3.
This addToPostBack
function is a variation of a common pre-jQuery technique I used to use to add functions to window.onload,
and it works well:
addToPostBack = function(func) {
var old__doPostBack = __doPostBack;
if (typeof __doPostBack != 'function') {
__doPostBack = func;
} else {
__doPostBack = function(t, a) {
if (func(t, a)) old__doPostBack(t, a);
}
}
};
$(document).ready(function() {
alert("Document ready.");
addToPostBack(function(t,a) {
return confirm("Really?")
});
});
Edit: Changed addToPostBack so that
I don't know how to do it with jQuery, but you could add an OnClientClick property to the ASP.NET control:
<asp:linkbutton id="TestButton" text="Click me!" runat="server" OnClientClick="alert('Submit detected.');" />
I've had success with a solution with overriding __doPostBack() so as to call an override on form.submit()
(i.e. $('form:first').submit(myHandler)
), but I think it's over-engineered. As of ASP.NET 2.0, the most simple workaround is to:
Define a javascript function that you want to run when the form is submitted i.e.
<script type="text/javascript">
function myhandler()
{
alert('you submitted!');
}
</script>
Register your handler function within your codebehind i.e.
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
ScriptManager.RegisterOnSubmitStatement(Page, Page.GetType(),
"myHandlerKey", "myhandler()");
}
That's all! myhandler()
will be called from straightforward button-input submits and automatic __doPostBack()
calls alike.