Search code examples
jqueryimagebuttonreplacesubmit

Change submit button to a loading image with jquery


On a lot of sites lately, I've seen buttons being replaced with loading/thinking images after they are pressed, to prevent double clicks and make sure the user knows something is going on before the page flickers off. In this case, nothing asynchronous is actually happening -- just a regular form submit.

How would I recreate this with jQuery?


Solution

  • Go the simplest way. Say your button is btnSubmit.

    <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" />
    <div id="divMsg" style="display:none;">
        <img src="../images/loading.gif" alt="Please wait.." />
    </div>
    

    Now using jquery, on click of the button:

    <script type="text/javascript">
         $('#btnSubmit').click(function(){
             $(this).attr('disabled','disabled');
             $('#divMsg').show();
             //your client side validation here
             if(valid)
                return true;
             else
                {
                  $(this).removeAttr('disabled');
                  $('#divMsg').hide();     
                  return false;
                }
         });
    </script>
    

    The submit button will be disabled, the animating image loading.gif will show up. And the page will postback. The benefit is that if validation fails you can again enable the submit button and hide the loading image. In such case, obviously you will show the error message.