Adding a “loading” image to (just about) any form on submit, with jQquery

under the category of the simplest thing that will actual work, I wanted to have one of those nice animate swilling icons running after the user hit the submit button so they knew that something was really happening.

The core code to this is very simple, using jQuery, just have a hidden image tag with the image (one on many “ajax loader images“, even though there is no Ajax involved in this case), use the jQuery .submit() function to bind the the event and show the image using the jQuery .show().

But want I wanted to do was use this across a large number of forms without customizing the forms or the javascript function very much or (even better) at all. Hence this code :

This is assuming there is only one form and only one submit type button.

The 3rd line is checking ( via ($(‘#loading_image’).length == 0) ) to see if the image tag has been previously been added to the form, and if not (length==0) inserts the image tag just before the submit button.

Also 2 notes about the img tag I’m inserting (just before the submit or update button) :

  • using the alt=”loading” give me a fail back if the image do not load (probably a img path problem).
  • I could insert more elaborate HTML mark up, even going a far a view point centered lightbox sort of effect.

As an added bonus, the last line disables the submit button to stop the user from resubmitting (or double submitting the form). very very bad.

One Reply to “Adding a “loading” image to (just about) any form on submit, with jQquery”

  1. A few notes:

    * This script assumes that there is only one form on the page (which may be a valid assumption depending on the situation). Element id’s are unique within the page, so you can’t (shouldn’t) add a second loading image with the same id.

    >> I had some exiting views with the element on it, so I was being extra paranoid by checking. I’m not sure that it is necessary, apart from bad DOM form, in having to elements with the same id since the $(‘#loading_image’) with stop at the first element it finds, so the worst that would happen is the $(‘#loading_image’) being shown is not the one you were expecting.

    * The submit handler exits before the call to disable the submit button, so the button will stay clickable.
    >> Ack! I will fix this!

    * What happens if the user hits the submit button, then cancels the form submission (and stays on the page)? If the button is disabled the user won’t be able to submit again without reloading the page.

    >> I’m being paranoid again.

    Otherwise, a useful script. Thanks for sharing!

Leave a Reply