Monday, March 8, 2010

JavaScript form submission gotcha

The other day I fighting with some bad form data and I wanted to have it checked before the form was submitted (plus on the server side).

The form is submitted using JavaScript (or javascript :), using: document.myForm.submit(). I would normally add a handler for this using prototype or YUI events but this is some pretty old (old old) code. So I thought I would use some of that sweet  onsubmit handler magic. Inline of course.

Something like:
<form action="/someaction" type="POST" name="myForm" onsubmit="return validate_form();">
...

Well to my frustrated amazement, the onsubmit handler didn't work. I thought maybe there was some strange caveat that prevent inline event handlers from working with javascript submitted forms.

I changed it to using the function pointer definition:
document.myForm.onsubmit = validate_form; 

Well that didn't work either, after some digging (and cursing), I came across a couple of references that indicated that low and behold, onsubmit events are not called when forms are triggered by javascript code.

This meant I need to add the validation to my own (well a previous persons code). This was a big ol' pain since it was being called in multiple places. Gah!

I did write a submit form wrapper that checked for an onsubmit handler and ran it as follows:
document.myForm.onsubmit = validate_form;

function submit_form( f ) {
  if ( f.onsubmit && !f.onsubmit() ) {
    return false;
  }

  f.submit();
}

It works and nothing seems to have flames shooting out of it. :)

2 comments:

  1. I hate it when I get flames!

    Someone should create a usb device for that: get a syntax error and 2 feet of flames shoot out the side of your laptop.

    ReplyDelete
  2. Do you have a full sample of this working??
    I've tried putting this into the javascript block in the head section..

    All I get is an error that says "document.myForm is undefined"

    ReplyDelete