天道酬勤,学无止境

Disable button on form submission

Question

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 javascript onclick but then if a client side validation that fails the button remains disabled.

How do I disable the button when the form successfully submits not just when the user clicks?

This is an ASP.NET form so I would like to hook in nicely with the asp.net ajax page lifecycle if possible.

Answer1

Give this a whirl:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

         // Identify button as a "disabled-when-clicked" button...
         WebHelpers.DisableButtonOnClick( buttonTest, "showPleaseWait" ); 
    }

    protected void buttonTest_Click( object sender, EventArgs e )
    {
        // Emulate a server-side process to demo the disabled button during
        // postback.
        Thread.Sleep( 5000 );
    }
}



using System;
using System.Web;
using System.Web.UI.WebControls;
using System.Text;

public class WebHelpers
{
    //
    // Disable button with no secondary JavaScript function call.
    //
    public static void DisableButtonOnClick( Button ButtonControl )
    {
        DisableButtonOnClick( ButtonControl, string.Empty );    
    }

    //
    // Disable button with a JavaScript function call.
    //
    public static void DisableButtonOnClick( Button ButtonControl, string ClientFunction )
    {   
        StringBuilder sb = new StringBuilder( 128 );

        // If the page has ASP.NET validators on it, this code ensures the
        // page validates before continuing.
        sb.Append( "if ( typeof( Page_ClientValidate ) == 'function' ) { " );
        sb.Append( "if ( ! Page_ClientValidate() ) { return false; } } " );

        // Disable this button.
        sb.Append( "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 ) ) 
        {
            sb.AppendFormat( "if ( typeof( {0} ) == 'function' ) {{ {0}() }};", ClientFunction );  
        }

        // GetPostBackEventReference() obtains a reference to a client-side script function 
        // that causes the server to post back to the page (ie this causes the server-side part 
        // of the "click" to be performed).
        sb.Append( ButtonControl.Page.ClientScript.GetPostBackEventReference( ButtonControl ) + ";" );

        // Add the JavaScript created a code to be executed when the button is clicked.
        ButtonControl.Attributes.Add( "onclick", sb.ToString() );
    }
}
Answer2

I'm not a huge fan of writing all that javascript in the code-behind. Here is what my final solution looks like.

Button:

<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" OnClientClick="doSubmit(this)" />

Javascript:

<script type="text/javascript"><!--
function doSubmit(btnSubmit) {
    if (typeof(Page_ClientValidate) == 'function' && Page_ClientValidate() == false) { 
        return false;
    }    
    btnSubmit.disabled = 'disabled';
    btnSubmit.value = 'Processing. This may take several minutes...';
    <%= ClientScript.GetPostBackEventReference(btnSubmit, string.Empty) %>;    
}
//-->
</script>
Answer3

The following function is useful without needing the disabling part which tends to be unreliable. Just use "return check_submit();" as part of the onclick handler of the submit buttons.

There should also be a hidden field to hold the form_submitted initial value of 0;

<input type="hidden" name="form_submitted" value="0">

function check_submit (){
            if (document.Form1.form_submitted.value == 1){
                alert("Don't submit twice. Please wait.");
                return false;
            }
            else{
                document.Form1.form_submitted.value = 1;
                return true;
            }
            return false;
    }
Answer4

Disable the button at the very end of your submit handler. If the validation fails, it should return false before that.

However, the JavaScript approach is not something that can be relied upon, so you should have something to detect duplicates on the server as well.

Answer5

if the validation is successful, then disable the button. if it's not, then don't.

function validate(form) {
  // perform validation here
  if (isValid) {
    form.mySubmitButton.disabled = true;
    return true;
  } else {
    return false;
  }
}

<form onsubmit="return validate(this);">...</form>
Answer6

Set the visibility on the button to 'none';


btnSubmit.Attributes("onClick") = document.getElementById('btnName').style.display = 'none';

Not only does it prevent the double submission, but it is a clear indicator to the user that you don't want the button pressed more than once.

Answer7

Not sure if this will help, but there's onsubmit event in form. You can use this event whenever the form submit (from any button or controls). For reference: http://www.htmlcodetutorial.com/forms/_FORM_onSubmit.html

Answer8

A solution will be to set a hidden field when the button is clicked, with the number 1.

On the button click handler first thing is to check that number if it is something other than 1 just return out of the function.

Answer9

You may also be able to take advantage of the onsubmit() javascript event that is available on forms. This event fires when the form is actually submit and shouldn't trap until after the validation is complete.

Answer10

This is an easier but similar method than what rp has suggested:

function submit(button) {
        Page_ClientValidate(); 
        if(Page_IsValid)
        {
            button.disabled = true;
        }
}

 <asp:Button runat="server" ID="btnSubmit" OnClick="btnSubmit_OnClick" OnClientClick="submit(this)" Text="Submit Me" />
Answer11

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);
}
Answer12

The correct (as far as user-friendliness is concerned, at least) way would be to disable the button using the OnClientClick attribute, perform the client-side validation, and then use the result of that to continue or re-enable the button.

Of course, you should ALSO write server-side code for this, as you cannot rely on the validation even being carried out due to a lack, or particular implementation, of JavaScript. However, if you rely on the server controlling the button's enabled / disabled state, then you basically have no way of blocking the user submitting the form multiple times anyway. For this reason you should have some kind of logic to detect multiple submissions from the same user in a short time period (identical values from the same Session, for example).

Answer13

one of my solution is as follow:

add the script in the page_load of your aspx file

    HtmlGenericControl includeMyJava = new HtmlGenericControl("script");
    includeMyJava.Attributes.Add("type", "text/javascript");
    includeMyJava.InnerHtml = "\nfunction dsbButton(button) {";
    includeMyJava.InnerHtml += "\nPage_ClientValidate();";
    includeMyJava.InnerHtml += "\nif(Page_IsValid)";
    includeMyJava.InnerHtml += "\n{";
    includeMyJava.InnerHtml += "\nbutton.disabled = true;";
    includeMyJava.InnerHtml += "}";
    includeMyJava.InnerHtml += "\n}";
    this.Page.Header.Controls.Add(includeMyJava);

and then set your aspx button parameters as follow:

<asp:Button ID="send" runat="server" UseSubmitBehavior="false" OnClientClick="dsbButton(this);" Text="Send" OnClick="send_Click" />

Note that "onClientClick" helps to disable to button and "UseSubmitBehaviour" disables the traditional submitting behaviour of page and allows asp.net to render the submit behaviour upon user script.

good luck

-Waqas Aslam

Answer14

Just heard about the "DisableOnSubmit" property of an <asp:Button>, like so:

<asp:Button ID="submit" runat="server" Text="Save"
    OnClick="yourClickEvent" DisableOnSubmit="true" />

When rendered, the button's onclick attribute looks like so:

onclick="this.disabled=true; setTimeout('enableBack()', 3000);
  WebForm_DoPostBackWithOptions(new
  WebForm_PostBackOptions('yourControlsName', '', true, '', '', false, true))

And the "enableBack()' javascript function looks like this:

function enableBack()
{
    document.getElementById('yourControlsName').disabled=false;
}

So when the button is clicked, it becomes disabled for 3 seconds. If the form posts successfully then you never see the button re-enable. If, however, any validators fail then the button becomes enabled again after 3 seconds.

All this just by setting an attribute on the button--no javascript code needs to be written by hand.

Answer15

So simply disabling the button via javascript is not a cross-browser compatible option. Chrome will not submit the form if you just use OnClientClick="this.disabled=true;"
Below is a solution that I have tested in Firefox 9, Internet Explorer 9, and Chrome 16:

<script type="text/javascript">
var buttonToDisable;
function disableButton(sender)
{
    buttonToDisable=sender;
    setTimeout('if(Page_IsValid==true)buttonToDisable.disabled=true;', 10);
}
</script>

Then register 'disableButton' with the click event of your form submission button, one way being:

<asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClientClick="disableButton(this);" />

Worth noting that this gets around your issue of the button being disabled if client side validation fails. Also requires no server side processing.

Answer16

Building on @rp.'s answer, I modified it to invoke the custom function and either submit and disable on success or "halt" on error:

public static void DisableButtonOnClick(Button ButtonControl, string ClientFunction)
{
    StringBuilder sb = new StringBuilder(128);

    if (!String.IsNullOrEmpty(ClientFunction))
    {
        sb.AppendFormat("if (typeof({0}) == 'function') {{ if ({0}()) {{ {1}; this.disabled=true; return true; }} else {{ return false; }} }};", ClientFunction, ButtonControl.Page.ClientScript.GetPostBackEventReference(ButtonControl, null));
    }
    else
    {
        sb.Append("return true;");
    }

    ButtonControl.Attributes.Add("onclick", sb.ToString());
}
Answer17

Came across rp's code in a legacy app of ours which was struggling with some crazy behaviour.

Tracked it down to a strange combination of event firing - when DisableButtonOnClick() was being used on an asp button inside an UpdatePanel, the POST would be sent twice (once by the doPostBack added by DisableButtonOnClick(), and once by the UpdatePanel). However, this only happened with some browsers (early versions of Edge, but not recent ones, and IE11 did this, Chrome and FireFox did not (at least the versions I tested with)). I presume Chrome and newer versions of Edge are dealing with this scenario internally in some way. Tracking the issue with F12 devtools in IE - the two POSTs happen so closely together that the first one gets immediately ABORTED, but under some conditions (network latency, user machine load, etc) the request does get through to the server before the browser can abort. So this results in a seemingly random double-post coming from button presses throughout the system, and it was a pain to trace back. The fix is to add a "return false;" after the doPostBack to prevent the UpdatePanel from getting involved when older browsers are in play.

TLDR - beware of this code on buttons in updatepanels. It's a good approach and nice method but has a potential issue in my (likely edge) case.

ps - I would have commented on rp's post but I don't have the rep. Thought it might be useful for future travelers.

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

相关推荐
  • Prevent double submission of forms in jQuery
    Question I have a form that takes a little while for the server to process. I need to ensure that the user waits and does not attempt to resubmit the form by clicking the button again. I tried using the following jQuery code: <script type="text/javascript"> $(document).ready(function() { $("form#my_form").submit(function() { $('input').attr('disabled', 'disabled'); $('a').attr('disabled', 'disabled'); return true; }); }); </script> When I try this in Firefox everything gets disabled but the form is not submitted with any of the POST data it is supposed to include. I can't use jQuery to submit
  • How do I cancel form submission in submit button onclick event?
    Question I'm working on an ASP.net web application. I have a form with a submit button. The code for the submit button looks like <input type='submit' value='submit request' onclick='btnClick();'>. I want to write something like the following: function btnClick() { if (!validData()) cancelFormSubmission(); } How do I do this? Answer1 You are better off doing... <form onsubmit="return isValidForm()" /> If isValidForm() returns false, then your form doesn't submit. You should also probably move your event handler from inline. document.getElementById('my-form').onsubmit = function() { return
  • JavaScript code to stop form submission
    Question One way to stop form submission is to return false from your JavaScript function. When the submit button is clicked, a validation function is called. I have a case in form validation. If that condition is met I call a function named returnToPreviousPage(); function returnToPreviousPage() { window.history.back(); } I am using JavaScript and Dojo Toolkit. Rather going back to the previous page, it submits the form. How can I abort this submission and return to the previous page? Answer1 You can use the return value of the function to prevent the form submission <form name="myForm"
  • Layer form validation and submission
    1. Layer form submission and verification method (add employee page)<form class="layui-form layui-form-pane1 pzjzsj" action=""> <div class="layui-form-item"> <label class="layui-form-label">手机号</label> <div class="layui-input-inline"> <input type="text" name="mobile" lay-verify="phone" placeholder="请输入手机号" autocomplete="off" class="layui-input" value="${PhomeUser.mobile }"/> </div> </div> <div class="layui-form-item"><label class="layui-form-label">Real name</label> <div class="layui-input-inline"> <input type="text" name="truename" lay-verify="required" placeholder="请输入姓名" autocomplete="off"
  • php $_POST array empty upon form submission
    Question I have a custom Content Management System (CMS) I've built that works perfectly on my dev box (Ubuntu/PHP5+/MySQL5+). I just moved it up to the production box for my client and now all form submissions are showing up as empty $_POST arrays. I found a trick to verify the data is actually being passed using file_get_contents('php://input'); and the data is showing up fine there -- the $_POST/$_REQUEST arrays are always empty. I've also verified the content-type headers are correct as well via firebug (application/x-www-form-urlencoded; charset=utf-8). This issue is happening regardless
  • jquery disable form submit on enter
    Question I have the following javascript in my page which does not seem to be working. $('form').bind("keypress", function(e) { if (e.keyCode == 13) { e.preventDefault(); return false; } }); I'd like to disable submitting the form on enter, or better yet, to call my ajax form submit. Either solution is acceptable but the code I'm including above does not prevent the form from submitting. Answer1 If keyCode is not caught, catch which: $('#formid').on('keyup keypress', function(e) { var keyCode = e.keyCode || e.which; if (keyCode === 13) { e.preventDefault(); return false; } }); EDIT: missed it
  • How to prevent form from being submitted?
    Question I have a form that has a submit button in it somewhere. However, I would like to somehow 'catch' the submit event and prevent it from occurring. Is there some way I can do this? I can't modify the submit button, because it's part of a custom control. Answer1 Unlike the other answers, return false is only part of the answer. Consider the scenario in which a JS error occurs prior to the return statement... html <form onsubmit="return mySubmitFunction(event)"> ... </form> script function mySubmitFunction() { someBug() return false; } returning false here won't be executed and the form
  • jQuery UI modal form crazy stepping on the pit
    Want to apply the front-end components to write a form validation page, so I tried jQuery UI Examples of official websites First paste the example from the official website: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jQuery UI Dialog - Modal form</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <style> label, input { display:block; } input.text { margin-bottom:12px; width:95%; padding: .4em; }
  • jQuery disable/enable submit button
    Question I have this HTML: <input type="text" name="textField" /> <input type="submit" value="send" /> How can I do something like this: When the text field is empty the submit should be disabled (disabled="disabled"). When something is typed in the text field to remove the disabled attribute. If the text field becomes empty again(the text is deleted) the submit button should be disabled again. I tried something like this: $(document).ready(function(){ $('input[type="submit"]').attr('disabled','disabled'); $('input[type="text"]').change(function(){ if($(this).val != ''){ $('input[type="submit"
  • jQuery Validation plugin: disable validation for specified submit buttons
    Question I have a form with multiple fields that I'm validating (some with methods added for custom validation) with Jörn Zaeffere's excellent jQuery Validation plugin. How do you circumvent validation with specified submit controls (in other words, fire validation with some submit inputs, but do not fire validation with others)? This would be similar to ValidationGroups with standard ASP.NET validator controls. My situation: It's with ASP.NET WebForms, but you can ignore that if you wish. However, I am using the validation more as a "recommendation": in other words, when the form is submitted
  • Prevent users from submitting a form by hitting Enter
    Question I have a survey on a website, and there seems to be some issues with the users hitting enter (I don't know why) and accidentally submitting the survey (form) without clicking the submit button. Is there a way to prevent this? I'm using HTML, PHP 5.2.9, and jQuery on the survey. Answer1 You can use a method such as $(document).ready(function() { $(window).keydown(function(event){ if(event.keyCode == 13) { event.preventDefault(); return false; } }); }); In reading the comments on the original post, to make it more usable and allow people to press Enter if they have completed all the
  • jQuery Ajax POST example with PHP
    Question I am trying to send data from a form to a database. Here is the form I am using: <form name="foo" action="form.php" method="POST" id="foo"> <label for="bar">A bar</label> <input id="bar" name="bar" type="text" value="" /> <input type="submit" value="Send" /> </form> The typical approach would be to submit the form, but this causes the browser to redirect. Using jQuery and Ajax, is it possible to capture all of the form's data and submit it to a PHP script (an example, form.php)? Answer1 Basic usage of .ajax would look something like this: HTML: <form id="foo"> <label for="bar">A bar<
  • Basic PHP and AJAX
    Question We have a large PHP system that I am changing to OOP and want to use AJAX to update the web pages for logged in users. I am completely self taught and good on HTML, CSS and PHP with a basic Javascript understanding. Trying to learn AJAX with PHP is defeating me. After trying a self made set of scripts to test AJAX which wouldn't work I then went to the Internet for examples and can't get any to work. This is on my development Mac running MAMP and using my host where we keep the current system. My question is, does anybody have a simple 'hello world' set of HTML and PHP scripts that
  • Disable validation of HTML5 form elements
    Question In my forms, I'd like to use the new HTML5 form types, for example <input type="url" /> (more info about the types here). The problem is that Chrome wants to be super helpful and validate these elements for me, except that it sucks at it. If it fails the built-in validation, there's no message or indication other than the element getting focus. I prefill URL elements with "http://", and so my own custom validation just treats those values as empty strings, however Chrome rejects that. If I could change its validation rules, that would work too. I know I could just revert back to using
  • Send email with PHP from html form on submit with the same script
    Question I want to send an email with PHP when a user has finished filling in an HTML form and then emailing information from the form. I want to do it from the same script that displays the web page that has the form. I found this code, but the mail does not send. <?php if (isset($_POST['submit'])) { $to = $_POST['email']; $subject = $_POST['name']; $message = getRequestURI(); $from = "zenphoto@example.com"; $headers = "From:" . $from; if (mail($to, $subject, $message, $headers)) { echo "Mail Sent."; } else { echo "failed"; } } ?> What is the code to send an email in PHP? Answer1 EDIT (#1) If