Disable a button on click

后端 未结 9 1517
栀梦
栀梦 2020-12-31 07:04

I have a button control. Once the user clicks on it, the click event should fire and then the button should get disabled. How can I do this? I have the option to use JQuery

相关标签:
9条回答
  • 2020-12-31 07:27

    For whatever reason, the HTML spec dictates that disabled elements should not be included in POST requests. So, if you use JavaScript to disable the HTML element in the client-side onclick event, the input element will be disabled when the browser assembles the POST request, the server won't be properly notified which element raised the postback, and it won't fire server-side click event handlers.

    When you set the UseSubmitBehavior property to false, ASP.NET renders an input element of type button instead of the regular input of type submit that the ASP.NET Button control normally generates. This is important because clicking a button element does not trigger the browser's form submit event.

    Instead of relying on a browser form submission, ASP.NET will render a client-side call to __doPostBack() within that button element's onclick handler. __doPostBack will raise the postback explicitly, regardless of what POST data comes through in the request.

    With the postback being raised independent of the browser submit event, you're freed of the previously mentioned HTML quirk. Then, you can set an OnClientClick of "this.disabled = true;", which will render as "this.disabled = true; __doPostBack('Button1', '');", and things will work as intended.

    0 讨论(0)
  • 2020-12-31 07:27

    You need to be careful that the postback occurs before you disable the button through client script. This is a common gotcha with ajax and input boxes. Disabling an input box prevents the data from being sent from the browser, even if you can see text within it while it is disabled. The answer is that you need to use jquery for this to ensure the server-side code runs first before it is disabled.

    -Oisin

    0 讨论(0)
  • 2020-12-31 07:31

    Have you tried this?

    Add an OnClientClick="MyFunction();" to your .NET button.

    Then in the .aspx page script tags you add the following JS function:

    <script type="text/javascript">
      function MyFunction()
      {
        window.setTimeout(function ()
        {
          // get the button/control to disable using your favourite clientside ...
          // ... control grabbing code snippet ...
          // ... eg. JQUERY $('Button1'), getElementById, etc.)
    
          document.getElementsByName('Button1').Button1.disabled = true;
    
          // I've used "getElementsByName" because .NET will render a button with
          // ... a "name" attribute, and not an "id" attribute, by default
    
        }, 1);
      }
    </script>
    

    This gives the browser a chance to post back, followed by a quick button disable.

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