views:

30

answers:

2

We are writing an ASP.NET MVC application. By default, if the client browser has Javascript, the handler for every form on the page is set, by Javascript, to be one that sends the submission down an Ajax "pipe" (progressive enhancement).

But, for one form (on a page of several), I'd like this handler to be bypassed/ignored. Is there a simple way to do this? Perhaps by overriding the handler by specifying my own onsubmit event directly in the DOM - or some other method?

We use jQuery, so those libraries are available to me.

+1  A: 

I would most likely solve this by assigning some distinctive attribute to the form that breaks with your standards (the one that should not have AJAX behavior) - something like class="oldschool". In the JavaScript code, when hooking up the submit event handler on forms, I would then make sure to exclude any forms with this special mark:

$('form:not(.oldschool)').submit(function() {
    // Do fancy AJAX stuff
});

Update: In order not to change any external JavaScript files, and have the new behavior introduced simply by altering the HTML markup, consider doing something like this:

<form ... onsubmit="if (typeof $ == 'function') $(this).unbind('submit');">

It is no beauty, but it seems to get the job done - at least in the browsers I have available here.

Jørn Schou-Rode
Great idea. I would prefer a way of neutralising the Javascript form handler from the DOM, as I do not have intellectual "ownership" of the "fancy" ajax Javascript code, however, I will consider your approach as a fallback position.
Ben Aston
@Ben: How about unregistering the event handler from the form in a script executed *after* the one that you do not own? Would that be possible?
Jørn Schou-Rode
@Ben: If the solution proposed in my last comment is also no-go, see the wacky, hacky solution in my updated answer :)
Jørn Schou-Rode
- Many thanks :)
Ben Aston
I used your "wacky hacky" solution to good effect. When you say typeof $ == 'function', what does $ represent? The handler associated with the event?
Ben Aston
`$` would be the jQuery function. The `if` statement checks that jQuery is indeed available, to avoid raising an error if the user submits the form *really* fast, before external scripts are loaded.
Jørn Schou-Rode
+1  A: 

Although I'm not sure I understand what you mean by "from the DOM" I assume you can't change the original ajax/js code but you should be able to insert a little script tag somewhere which runs after the code that sets the ajax submit handler.

Further assuming that the handler set is in the form $("form").submit(...) or similar you could use this

$('selectorForYourForm').unbind('submit');

As this runs after the original js code it would unbind any handler the original code set for the submit action of this form.

jitter