Friday, April 10, 2009

Prevent users from hitting a submit button twice in a JSF application

I had this small JSF application and I was trying to implement something to prevent users from hitting a submit button twice.

Initially I tried to use Javascript to disable the button (from the onclick of the button).

However, when the button was disabled, the form was not submitted.

I found this from IBM and used it with a small change (added a “return” in the onclick event).

The overall concept is to implement a javascript function that detects that the submit button has been already clicked and call it from the onclick event of the form.

This is the javascript code:


<script>
var requestSubmitted = false;
       function submitRequest() {
           if (!requestSubmitted ) {
                     requestSubmitted  = true;
                    return true;
                }

              alert('Already submitted...')
              return false;
        }
</script>


And this is how it is invoked from the form :

<h:form id="searchForm" onsubmit="javascript:return submitRequest();">

Of course the button is not disabled, but at least the form is not being re-submitted.

No comments: