Wednesday, May 13, 2009

Turn the submit button off when it press in ASP.Net

Sometime, we need to turn the button off after user clicking to prevent the double actions. Let's say, when I developed 2C2P payment processor,  I have to disable the "Confirm" button to avoid the double payment transactions when user click the button once. Otherwise, we will have the complaint from user about duplicated transactions when user might click the button double times since page loading is slow (behind scene, it's processing). The following example show you that it turn the submit button off and show message when it press using server-side script.

Disable button after clicking

Here is button control to add <form> tag.
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" Width="97px" />

Put the following code to code-behind as below.
protected void Page_Load(object sender, EventArgs e)
            this.Button1.Attributes.Add("onclick", "this.value='Please wait...';this.disabled = true;"
                + Page.ClientScript.GetPostBackEventReference(this.Button1, ""));
protected void Button1_Click(object sender, EventArgs e)
            //Here go on for click event

Now, click the button every times, it disable itself and user don't have a chance to press the button double.

How to limit the text length as maximum with Javascript (Text Counter)

Here is the javascript text counter. When you write down the character in Textarea box, it show the available text count immediately and remove the extra text as well. Put the following javascript between <head> and </head> tag.
<script type="text/javascript">
function textCounter(field, countfield, maxlimit)
    if (field.value.length > maxlimit)
        field.value = field.value.substring(0, maxlimit);
        countfield.value = maxlimit - field.value.length;
Here is form tag.
<span>Only 200 char allowed</span>
<textarea id="comment" onblur="'#ffffff'" onfocus="'#FFFCF9'" onkeyup="textCounter(comment,textCount,200);" onkeydown="textCounter(comment,textCount,200);" rows="7" cols="60" name="comment" style="background-color: rgb(255, 255, 255);">
<input type="text" value="200" maxlength="3" size="3" id="textCount" name="textCount"/>
<span>Char count</span>

That's it. Enjoy the JScript!