Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

javascript - Preventing multiple clicks on button

I have following jQuery code to prevent double clicking a button. It works fine. I am using Page_ClientValidate() to ensure that the double click is prevented only if the page is valid. [If there are validation errors the flag should not be set as there is no postback to server started]

Is there a better method to prevent the second click on the button before the page loads back?

Can we set the flag isOperationInProgress = yesIndicator only if the page is causing a postback to server? Is there a suitable event for it that will be called before the user can click on the button for the second time?

Note: I am looking for a solution that won't require any new API

Note: This question is not a duplicate. Here I am trying to avoid the use of Page_ClientValidate(). Also I am looking for an event where I can move the code so that I need not use Page_ClientValidate()

Note: No ajax involved in my scenario. The ASP.Net form will be submitted to server synchronously. The button click event in javascript is only for preventing double click. The form submission is synchronous using ASP.Net.

Present Code

$(document).ready(function () {
  var noIndicator = 'No';
  var yesIndicator = 'Yes';
  var isOperationInProgress = 'No';

  $('.applicationButton').click(function (e) {
    // Prevent button from double click
    var isPageValid = Page_ClientValidate();
    if (isPageValid) {
      if (isOperationInProgress == noIndicator) {
        isOperationInProgress = yesIndicator;
      } else {
        e.preventDefault();
      }
    } 
  });
});

References:

  1. Validator causes improper behavior for double click check
  2. Whether to use Page_IsValid or Page_ClientValidate() (for Client Side Events)

Note by @Peter Ivan in the above references:

calling Page_ClientValidate() repeatedly may cause the page to be too obtrusive (multiple alerts etc.).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found this solution that is simple and worked for me:

<form ...>
<input ...>
<button ... onclick="this.disabled=true;this.value='Submitting...'; this.form.submit();">
</form>

This solution was found in: Original solution


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...