0

I have following script to prevent a button from submitting twice by double clicking. It works fine.

But the scenario gets clumsy when I added a Required Field validator. If I try to submit with a blank value in textbox, the validator fires. But when I entered value in textbox and try to submit again it does not do a postback.

I understand the reason, in the first button click itself, the variable isActionInProgress is set as 'Yes' irrespective of the validation error.

What is the best way to overcome this challenge?

MARK UP

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.1.js"></script>
<script type="text/javascript">

    $(document).ready(function () {



        var isActionInProgress = 'No';

        $('.myButton').click(function (e) {

            if (isActionInProgress == 'No') {
                isActionInProgress = 'Yes';
            }
            else {
                e.preventDefault();
                //alert('STOP');
            }

        });


    });

</script>
</head>
<body>
<form id="form1" runat="server">
<div>
    <asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" CssClass="myButton" runat="server" Text="Submit" ValidationGroup="ButtonClick"
        OnClick="Button1_Click" />

    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="txtEmpName"
        runat="server" ErrorMessage="RequiredFieldValidator" ValidationGroup="ButtonClick" Text="*"></asp:RequiredFieldValidator>
</div>
</form>
</body>

REFERENCES

  1. Page_ClientValidate is validating multiple times.
  2. Hide redundant error message in ASP.Net ValidationSummary
  3. MSDN - ASP.NET Validation in Depth
Community
  • 1
  • 1
LCJ
  • 22,196
  • 67
  • 260
  • 418

1 Answers1

2

I think somthin like this:

 $('.myButton').click(function (e) {
        if(Page_IsValid){
        if (isActionInProgress == 'No') {
            isActionInProgress = 'Yes';
        }
        else {
            e.preventDefault();
            //alert('STOP');
        }
      }

    });
Boriss Pavlovs
  • 1,441
  • 12
  • 8
  • 2
    If validator validate correct Page_IsValid will be true. Your click doesn't fire after validation because your script works in any case and prevent second click. Now this occures only if validation was correct – Boriss Pavlovs Dec 11 '12 at 17:55