views:

15537

answers:

4

I've got a page with a normal form with a submit button and some jQuery which binds to the form submit event and overrides it with e.preventDefault() and runs an AJAX command. This works fine when the submit button is clicked but when a link with onclick='document.formName.submit();' is clicked, the event is not caught by the AJAX form submit event handler. Any ideas why not or how to get this working without binding to all the a elements?

+5  A: 

If you are using jQuery, you should be attaching events via it's own event mechanism and not by using "on" properties (onclick etc.). It also has its own event triggering method, aptly named 'trigger', which you should use to activate the form submission event.

Eran Galperin
I concur - don't use obtrusive JavaScript in your code, it just makes for headaches if you are mingling unobtrusive JavaScript with it.
Jason Bunting
+1  A: 

Thanks Eran

I am using this event binding code this._form.bind('submit', Delegate.create(this, function(e) { e.preventDefault();; this._searchFadeOut(); this.__onFormSubmit.invoke(this, new ZD.Core.GenericEventArgs(this._dateField.attr('value')));

but there is legacy onclick code on the html and I would prefer not to change it as there are just so many links.

The problem is that calling the form's submit() method will not activate the event. It's the same with an input focus() method - they simply do not go through the regular event delegation chain.
Eran Galperin
+17  A: 

A couple of suggestions:

  • Overwrite the submit function to do your evil bidding

    var oldSubmit = form.submit;
    form.submit = function() {
        $(form).trigger("submit");
        oldSubmit.call(form, arguments);
    }
  • Why not bind to all the <a> tags? Then you don't have to do any monkey patching, and it could be as simple as (assuming all the links are inside the form tag):

    $("form a").click(function() {
        $(this).parents().filter("form").trigger("submit");
    });
stechz
A: 

Thanks guys!