[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.).

This question is related to javascript jquery

The answer is


using count,

 clickcount++;
    if (clickcount == 1) {}

After coming back again clickcount set to zero.


JS provides an easy solution by using the event properties:

$('selector').click(function(event) {
  if(!event.detail || event.detail == 1){//activate on first click only to avoid hiding again on multiple clicks
    // code here. // It will execute only once on multiple clicks
  }
});

We can use on and off click for preventing Multiple clicks. i tried it to my application and it's working as expected.

$(document).ready(function () {     
    $("#disable").on('click', function () {
        $(this).off('click'); 
        // enter code here
    });
})

After hours of searching i fixed it in this way:

    old_timestamp == null;

    $('#productivity_table').on('click', function(event) {

    // code executed at first load
    // not working if you press too many clicks, it waits 1 second
    if(old_timestamp == null || old_timestamp + 1000 < event.timeStamp)
    {
         // write the code / slide / fade / whatever
         old_timestamp = event.timeStamp;
    }
    });

Disable pointer events in the first line of your callback, and then resume them on the last line.

element.on('click', function() {
  element.css('pointer-events', 'none'); 
  //do all of your stuff
  element.css('pointer-events', 'auto');   
};

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


I modified the solution by @Kalyani and so far it's been working beautifully!

$('selector').click(function(event) {
  if(!event.detail || event.detail == 1){ return true; }
  else { return false; }
});

Just copy paste this code in your script and edit #button1 with your button id and it will resolve your issue.

 <script type="text/javascript">
                $(document).ready(function(){  
                     $("#button1").submit(function() {
                            $(this).submit(function() {
                                return false;
                            });
                            return true;
                        }); 
        });
     </script

One way you do this is set a counter and if number exceeds the certain number return false. easy as this.

var mybutton_counter=0;
$("#mybutton").on('click', function(e){
    if (mybutton_counter>0){return false;} //you can set the number to any
    //your call
     mybutton_counter++; //incremental
});

make sure, if statement is on top of your call.


May be this will help and give the desired functionality :

_x000D_
_x000D_
$('#disable').on('click', function(){_x000D_
    $('#disable').attr("disabled", true);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id="disable">Disable Me!</button>_x000D_
<p>Hello</p>
_x000D_
_x000D_
_x000D_


you can use jQuery's [one][1] :

.one( events [, data ], handler ) Returns: jQuery

Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

see examples:

using jQuery: https://codepen.io/loicjaouen/pen/RwweLVx

// add an even listener that will run only once
$("#click_here_button").one("click", once_callback);

This should work for you:

$(document).ready(function () {
    $('.applicationButton').click(function (e) {
        var btn = $(this),
            isPageValid = Page_ClientValidate(); // cache state of page validation
        if (!isPageValid) {
            // page isn't valid, block form submission
            e.preventDefault();
        }
        // disable the button only if the page is valid.
        // when the postback returns, the button will be re-enabled by default
        btn.prop('disabled', isPageValid);
        return isPageValid;
    });
});

Please note that you should also take steps server-side to prevent double-posts as not every visitor to your site will be polite enough to visit it with a browser (let alone a JavaScript-enabled browser).


disable the button on click, enable it after the operation completes

$(document).ready(function () {
    $("#btn").on("click", function() {
        $(this).attr("disabled", "disabled");
        doWork(); //this method contains your logic
    });
});

function doWork() {
    alert("doing work");
    //actually this function will do something and when processing is done the button is enabled by removing the 'disabled' attribute
    //I use setTimeout so you can see the button can only be clicked once, and can't be clicked again while work is being done
    setTimeout('$("#btn").removeAttr("disabled")', 1500);
}

working example


If you are doing a full round-trip post-back, you can just make the button disappear. If there are validation errors, the button will be visible again upon reload of the page.

First set add a style to your button:

<h:commandButton id="SaveBtn" value="Save"
    styleClass="hideOnClick"
    actionListener="#{someBean.saveAction()}"/>

Then make it hide when clicked.

$(document).ready(function() {
    $(".hideOnClick").click(function(e) {
        $(e.toElement).hide();
    });
});