Friday, October 26, 2018

ASP.NET Prevent double-clicking of buttons

If you have a button that causes a record to be inserted into a table, you can sometimes run into duplicate records if the user happens to click the button twice (double-click).  This can be prevented by using javascript to disable the button as soon as the button is clicked the first time.  Use the following code:

<script>

    function disableButton() {
        document.getElementById("ID_OF_BUTTON").disabled = true;
    }

</script>


Then, use the OnClientClick property of the button to call this code:

<asp:Button ID="ID_OF_BUTTON" runat="server" Text="Click Me" OnClientClick="disableButton();" UseSubmitBehavior="false" />


NOTE: I have not used this on a form that has client validation, so I'm not sure how of if this would work in that situation.