Skip to content

jonocode – a developer's blog

I moved! –> http://pressreload.com

Tag Archives: jQuery

It happens.

Not often, but once in a while a user submits the same thing. Twice, maybe three times, and each just a second or two apart.

It’s easy to understand why. They click the submit button and then … nothing happens. If it doesn’t work right away, we assume it’s not working. The solution? Hit the button again! Hit it five times until finally, it seems to work.

There are two things you need to do to stop this from happening.

  1. Assure the user they successfully clicked the button, and they only have to wait a moment for the form to be processed.
  2. Stop the user from hitting the button again.

I’m a jQuery newbie, but it wasn’t long before I was in love with this javascript library. Here is my solution:

  1. Download the jQuery library if you haven’t already, and drop it in your js directory if you’re using Symfony.
  2. Reference the jquery library in your template, like so:
    <?php use_javascript('jquery') ?>
    
  3. And finally, here’s the source code:
<script type="text/javascript">
  $(document).ready(function(){
    $("input[type='submit']").attr("disabled", false);

    $("form").submit(function(){
      $("input[type='submit']").attr("disabled", true).val("Please wait...");
      return true;
    })
  })
</script>

I love the simplicity.

Once the document is ready, make sure every submit button on the page is enabled. In Firefox 3.5, if I click the back button to go back to the form after submitting, the submit button stays disabled. I’m not sure why; the value attribute is correct, but it stays disabled, even if you refresh.

In the next few statements, I add an onsubmit event to the form. If you have javascript validation on your form, you’ll have to execute your validation from within this function.

The function finds all submit buttons within the form, disables them, and changes their value to “Please wait…”. All of this is done dynamically, without altering the form directly in my html. Love it.

Does anyone have any server-side solutions to this problem? If you do I’d love to hear about them.

Tags: ,