Change submit button to a loading image with jquer

2019-03-21 03:11发布

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.

Know of any good tutorials for how to do this?

9条回答
看我几分像从前
2楼-- · 2019-03-21 03:48

Use .replaceWith():

$(".submitButton").click(function () {
    $(this).replaceWith("<img src='loading.gif'>");
});
查看更多
虎瘦雄心在
3楼-- · 2019-03-21 03:51

This replaces all submit inputs with an image onsubmit of the form

$(function() {
    $("form").submit(function() {
        $(":submit").replaceWith('<img src="/loading.gif" />');
    });
});

You may also want to disable submitting the form again, in case the user hits enter in a form field...

$(function() {
    // only run this handler on the first submit of the form 
    $("form").one("submit", function() {
        // replace all submit inputs with an image
        $(":submit").replaceWith('<img src="/loading.gif" />');  
        // don't let this form be submitted again
        $(this).submit(function() { return false; });
    });
});
查看更多
神经病院院长
4楼-- · 2019-03-21 03:52

Any of the above "replacing" strategies will work, but keep one thing in mind: If you aren't posting back (e.g. webforms), but posting to a different page (e.g. MVC), the user will be able to click back. At this point the button will be hidden and all you will see is a spinner.

I kept running into this problem and found that if you set the unload attribute of the BODY tag to a blank "", this will sort of "default" the page back to its original state. I guess this clears out your browser's cached version of the page so it will know to go back to the original version where the spinner was hidden. After I added this blank unload, it fixed the issue. I've tried it on FF and Chrome so far

查看更多
登录 后发表回答