I am trying to attach an event handler to form.submit on asp.net rendered pages with no success. I want to intercept every postback, and doc. says that I should be able. Am I doing something wrong?
$(document).ready(function() {
$("form").submit(function() {
alert('Form submit');
debugger;
});
});
Don't know if you are still looking for it, but here is the solution I have. I don't think it works with event canceling if using, say, stopPropagation() but it will let you run some script before submitting the form.
<script type="text/javascript">
$(function () {
var oldSubmit = __doPostBack;
var newSubmit = function (eventTarget, eventArgument) {
alert('custom submit function');
return oldSubmit(eventTarget, eventArgument);
};
__doPostBack = newSubmit;
});
</script>
This is something I did on a legacy WebForm application:
//trigger jquery form submit event handlers on __doPostBack
$(function() {
var oldPostBack = __doPostBack;
__doPostBack = function() {
$("form").triggerHandler("submit");
oldPostBack.apply(this, arguments);
};
});
This allows you to wire "submit" events using jQuery the way you normally would:
$("#myForm").submit(function() { alert("submitted!"); });
Typical doPostBack hijacking, but only once. It triggers "submit" handlers on any form elements before doing the old postback. This is necessary because, while asp.net does call the onsubmit function attached to the form dom object, it doesn't look like jquery's events work that way.
asp.net webforms are generally enveloped in only one big form (hence the term web forms).
if I'm not mistaken, all links and submit buttons call __doPostBack manually, so it bypasses the calling form submit and delegates that responsibility to the __doPostBack function.
you would probably need to overwrite this function.
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['aspnetForm'];
if (!theForm) {
theForm = document.aspnetForm;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
though I'm trying to understand your "debugger;" line in your function. perhaps it should be this?
$(document).ready(function() {
$("form").submit(function() {
alert('Form submit');
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With