jQuery form submit handling and inline onsubmit woes

jQuery’s event handling triggers in the bubbling phase, which is fine for most usage. I had to write some JavaScript to traps the submission of forms on any webpage, naturally, I wrote something like this:

$('form').each(function(e){
  $(e).submit(function(e){
    console.log("submitted!");
}

This works for most forms, but since we don’t have any control of what types of forms our users put on their sites, it doesn’t work in 2 cases: (a) when there is an inline onsubmit on the form tag, this is pretty common, the Feedburner email subscribe form does this, and (b) when the form is within an iframe on the page.

The fix for (a) is not trivial, I found out that the bind submit event is called after the inline onsubmit, so first thought was to put what I need to do on submit into a function, and prepend that in the onsubmit. However, this didn’t work as $(‘form#some-id’).attr(“onsubmit”, “blah”) didn’t set the value. So after a bit of experimenting, I ended up having to remove that attribute, but remember the contents of it and call it in an annon function at the end of execution, it looks like this:

$('form').each(function(i,e){
  var onsubmit = $(e).attr("onsubmit");
  if (onsubmit != null) {
    $(e).removeAttr('onsubmit');
    onsubmit = new Function(onsubmit);
  }
  $(e).submit(function(e){
    console.log("submit pressed!");
    if (onsubmit != null) onsubmit();
  })
})

Now on to finding a solution for the (b) iframe case.

, , ,

No comments yet.

Leave a Reply