Radu Cotescu's professional blog

g33k w17h pa45510n

jQuery .click() and the Double Submit of a Form

jQuery is one of the greatest JavaScript frameworks with plenty of documentation for just about everything one can do with it. In my latest project I have used jQuery extensively for any UX aspect: form validations, dialogs, error messages, AJAX, UI, etc.

A feature that I would really like to see implemented on all HTML forms is the ability to submit the form by using the Return key as well. I am sure that there are a lot of users who really like to keep their hands on the keyboard as much as possible, without using the mouse just to click a button or without hitting the TAB key in order to focus on the submit button after which to press Return. Some of the particularities of my project are the fact that it uses Struts2 and the Struts2 jQuery plugin. This plugin allows developers either to use the .jar embedded JavaScript libraries or to automatically get the required files from Google’s servers (CDN). In July, when my project was using Oracle 11G and TopLink everything worked okay. Now, after I have migrated the project to open-source solutions (MySQL and EclipseLink) I have noticed that whenever I tried to create a new account into the application I would get 2 submits for one action. At first I thought that this had something to do with EclipseLink. After some debugging I actually found out that it was a JavaScript issue (it is possible that now I’m using another jQuery UI release).

The problem

The code responsible for the issue is the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
$('#newProfileForm input:submit').button().click(function(e) {
    if(checkInputs()) {
        $('#newProfileForm form').submit();
    }
});
$('#newProfileForm input').keyup(function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if(code == 13) {
        if(checkInputs()) {
            $('#newProfileForm').submit();
        }
   }
});

What I have discovered is that the .click() handler actually binds itself to keyboard events too, not only mouse events. This means that if the user presses the Return button the event will be identified with a click event.

The solution

Even though if the behaviour mentioned previously is unexpected (who would have thought that a click event would be triggered by the keyboard even if the focus is not set on the submit button?!), there are two ways of avoiding it in the code above:

  1. eliminate the .keyup() handler because pressing on the Return button will be considered a click event;

  2. alter the first bind for the .click() handler like this:

1
2
3
4
5
6
$('#newProfileForm input:submit').button().click(function(e) {
    e.preventDefault(); // stop the browser's default behaviour
    if(checkInputs()) {
        $('#newProfileForm form').submit();
    }
});

Have you ever had similar problems?

Code

« The art of web feeds Ubuntu 10.10 and VirtualBox Guest Additions »

Comments