Friday, July 9, 2010

Fun and Games with onsubmit()

I've been doing programming for the browser interface for quite a few years now (maybe as far back as 1998, using Progress WebSpeed 2.X), and still, I'm learning things all the time.

Todays lesson was the form event, onsubmit().

With some actions in a web page, you want to make sure that some things are really meant to happen, for example, if you are deleting an entity from a back end database. The first defense (after authentication and access control lists) against accidental actions is making sure the delete gets issued as a POST, rather than a GET. And if you're paranoid enough, the next step is getting a confirmation from the user, since some users are still prone to jittery fingers and random clickiness.

So, I have this page where timesheets can be submitted for approval, deleted, and a bunch of other actions. Actions like approval, rejection, submission and deletion all have a confirmation, using the javascript confirm() function.

Side note: Is that the right spelling? Delete is to deletion, as submit is to submi.....?

And all the forms asking these confirmations had them set up on the onsubmit event handle for the forms in question.

Now, my menu structure is a bit special, so for the most part, there is not an actual form to fill out. When the user selects the Submit action from the menu, I programmatically trigger the submit event on the form, via submit(), and would expect the onsubmit handler to be called, run the confirmation and either submit or not submit based on the user selection of Yes or No, Okay or Cancel, or whatever confirm() does in your flavour of browser.

It turns out, onsubmit() is not supposed to be trigger programmatically. It's only supposed to be triggered if there is a submit button in the form, and a human selects that submit button. In my experience with Firefox 3.6.6 and Chrome 5.0.375.99, the onsubmit() function gets run, but the return value of the event handler is totally ignored.

This pretty much makes onsubmit quite useless as a catchall for validating a form, regardless of how the form is submitted.

In the end, I created a regular Javascript function for each confirmation type (i.e. confirmSubmit(), confirmApprove(), etc), and placed onclick events on each menu link to call that function. (i.e. onclick="confirmSubmit(); return false;").

In the function, I can call confirm() and then call form.submit() based on the results.

I've compromised with my programming principals for this one, since there doesn't seem any other option that is as simple to maintain. The only saving grace is that these forms do not have a visible aspect on the screen. The other forms on the page that actually take user input are making extensive usage of jQuery, dialog and validate.

No comments:

Post a Comment