Disable button on form submission

前端 未结 17 1714
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 00:13

I have a button that I would like to disable when the form submits to prevent the user submitting multiple times.

I have tried naively disabling the button with java

17条回答
  •  感情败类
    2020-12-01 01:16

    Note that rp's approach will double submit your form if you are using buttons with UseSubmitBehavior="false".

    I use the following variation of rp's code:

    public static void DisableButtonOnClick(Button button, string clientFunction)
    {
        // If the page has ASP.NET validators on it, this code ensures the
        // page validates before continuing.
        string script = "if (typeof(Page_ClientValidate) == 'function') { "
                + "if (!Page_ClientValidate()) { return false; } } ";
    
        // disable the button
        script += "this.disabled = true; ";
    
        // If a secondary JavaScript function has been provided, and if it can be found, call it.
        // Note the name of the JavaScript function to call should be passed without parens.
        if (!string.IsNullOrEmpty(clientFunction))
            script += string.Format("if (typeof({0}) == 'function') {{ {0}() }} ", clientFunction);
    
        // only need to post back if button is using submit behaviour
        if (button.UseSubmitBehavior)
            script += button.Page.GetPostBackEventReference(button) + "; ";
    
        button.Attributes.Add("onclick", script);
    }
    

提交回复
热议问题