Monday, January 21, 2013

Prevent multiple clicks on button

More often programmers need to prevent the multiple clicks on button. We can prevent the multiple clicks just by disable or hide the button after the first click and enable or show it again when the processing in done. We can also show the message at the time of processing to user.Here in the images shown below, I have just show you the scenario before and after the postback.


If you are using Ajax processing on button click, just disable the button when it is clicked and enable it when the Ajax processing is done. If you are using full postback on button click, you may just make the button invisible using client-side-scripting when the click occurs. And you don't need to worry about making it visible since after postback the page will be rendered again, with the button visible as usual. In the code snippet below I have shown how to ‘invisible’ the button from client side when it is clicked.

1- Aspx page

<form id="form1" runat="server">
    <div>
        <asp:Label ID="lblMsg" runat="server" ></asp:Label>
        <br />
        <asp:Button ID="btnClick" runat="server" Text="Click Me"
            onclick=" btnClick_Click" />
            <span id="spanMsg" style="display:none">Processing...</span>
    </div>
 </form>

2- Client Script function

<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
        $(function () {
            $('[id$=btnClick]').click(function () {

                $(this).css('display', 'none');
                $('span#spanMsg').show();

            });
        });
 </script>

3- Code Behind
 
protected void btnClick_Click(object sender, EventArgs e)
{
   lblMsg.Text = "Clicked at : "+DateTime.Now.ToString() + " <br /> " + lblMsg.Text;
}

That’s all. Here I am catching the click event of button and make it invisible. Meantime I am showing “Processing...” message to the user.

Happy Coding!! 
 
kick it on DotNetKicks.com

No comments:

Post a Comment

^ Scroll to Top