Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: form.submit(fn) does not work with Asp.net?

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;
    });
});
like image 898
epitka Avatar asked Jan 15 '10 17:01

epitka


3 Answers

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>
like image 183
BillRob Avatar answered Nov 16 '22 22:11

BillRob


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.

like image 33
InvisibleBacon Avatar answered Nov 16 '22 20:11

InvisibleBacon


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');
    });
}); 
like image 40
michael herndon Avatar answered Nov 16 '22 21:11

michael herndon