Preventing double submits with jQuery

A frequently encountered question amongst web developers is how to prevent forms from beeing submitted twice when the user double clicks on a button. There are existing solutions for this common problem by offering a unique transaction token that is evaluated on the server side (the JSF Spec 2.2 will come up with such a solution as you can see here). But form submission happens on the client side, so why would you want to evaluate requests that should have never been submitted?

Like so often, jQuery is your friend in this case. My solution (for a JSF application) is to simply remove the clicked link/button from the DOM on the first click:

<h:commandLink
id="back"
styleClass="someClass"
value="get Back"
action="#{myBean.backAction}"
onclick="$(this).remove()" />

While this is already a working solution, you might be unhappy with the link disappearing before the next page is rendered. In this case you can simply replace it with a dummy element (that appears like the original link) using a simple function:

function preventDoubleSubmit(element) {
var cssClass = element.attr('class');
var text = element.text();

var replacement = $("<b></b>).attr('href','#')
.attr('class',cssClass)
.text(text);

element.replaceWith(replacement);
return true;
}
<h:commandLink
id="back"
styleClass="someClass"
value="get Back"
action="#{myBean.backAction}"
onclick="preventDoubleSubmit($(this));" />

That should do the trick …

Short URL for this post: http://wp.me/p4nxik-tl
This entry was posted in Java Web Frameworks and tagged , , . Bookmark the permalink.

4 Responses to Preventing double submits with jQuery

  1. alfons says:

    Nice post.
    For button it would be possible to remove e.g. the onclick attribute.
    For better usability you may could add a different styleClass indicating the button is disabled.

    • alfons says:

      “For button it would be possible to remove e.g. the onclick attribute.” is not correct.
      Adding attr(‘disabled’,’true’) would do it.

  2. Larry says:

    Hi,

    I’ve tried implementing your solution but the function is never called and neither is my bean action. Can you please tell me what I’m doing wrong?

    function preventDoubleSubmit(element) {
    alert(2);
    var cssClass = element.attr(‘class’);
    var text = element.text();

    var replacement = $(“).attr(‘href’,’#’)
    .attr(‘class’,cssClass)
    .text(text);
    element.replaceWith(replacement);
    return true;
    }

    ….

    thanks

Leave a Reply