Why doesn't my form post when I disable the submit button to prevent double clicking?

后端 未结 10 1264
广开言路
广开言路 2020-12-31 19:06

Like every other web developer on the planet, I have an issue with users double clicking the submit button on my forms. My understanding is that the conventional way to han

相关标签:
10条回答
  • 2020-12-31 19:49
    document.getElementById('form1').onsubmit = function() {
        document.getElementById('btn').disabled = true;
    };
    
    0 讨论(0)
  • 2020-12-31 19:49

    Make sure that your javascript function returns true (or a value that would evaluate to boolean true), otherwise the form won't get submitted.

    function btn_click()
    var chk = document.getElementById("chk");
        if(chk.checked)
        {
                var btn = document.getElementById("btn");
                btn.disabled = true;
                return true;   //this enables the controls action to propagate
        }
        else    return false;  //this prevents it from propagating
    }
    
    0 讨论(0)
  • 2020-12-31 19:50

    We use the following JQuery script, to disable all buttons (input type=submit and button), when one button is clicked.

    We just included the script in a global JavaScript file, so we don't have to do remember anything when creating new buttons.

    $(document).ready(function() {
        $(":button,:submit").bind("click", function() {
            setTimeout(function() {
                $(":button,:submit").attr("disabled", "true");
            }, 0);
        });
    });
    

    This script could easily be extended with a check for Page_ClientValidate().

    0 讨论(0)
  • 2020-12-31 19:53

    This is the correct and simple way to do this:

    It works in all browsers (unlike the accepted solution above).

    Create a helper method in your application (say in a Utlity Namespace):

        Public Shared Sub PreventMultipleClicks(ByRef button As System.Web.UI.WebControls.Button, ByRef page As System.Web.UI.Page)
            button.Attributes.Add("onclick", "this.disabled=true;" + page.ClientScript.GetPostBackEventReference(button, String.Empty).ToString)
        End Sub
    

    Now from the code behind of each of your web pages you can simply call:

        Utility.PreventMultipleClicks(button1, page)
    

    where button1 is the the button you want to prevent multiple clicks.

    What this does is simply sets the on click handler to: this.disabled=true

    and then appends the buttons own post back handler, so we get:

    onclick="this.disabled=true";__doPostBack('ID$ID','');"

    This does not break the default behaviour of the page and works in all browsers as expected.

    Enjoy!

    0 讨论(0)
提交回复
热议问题