简体   繁体   中英

Disable click handler when click is fired in jQuery

We have a website built in .NET and jQuery. We have custom jQuery to call the load method on a processing ASP.NET page. That ajax call is fired in a click handler, eg

$("#Submit").click(function(){
  $(a_selector).load("Process.aspx?data=" + someDataObject, null, function(){
    alert("Done")});
  }
  return false;
);

Our issue is when we hit the #Submit button the click is fired which calls the ajax to process it. People seem to be double-clicking the button and therefore we're getting multiple results in our database from the dual clicks. Does anyone have an idea on how to prevent this issue? I considered something like disabling the button via JS but I'd like to know of other ideas.

Use the one function of jQuery. This way, the event is only ever fired once. Of course, you should also disable the button so the user knows that clicking on it is futile. In addition, show a spinner, progress bar, or change the cursor styling to indicate to the user that something is happening and the system isn't stuck.

$("#Submit").click(function(){
  $(a_selector).removeClass("class").load("Process.aspx?data=" + someDataObject, null, function(){
    $(this).addClass("class");
    alert("Done")});
  }
  return false;
);

Then just add some specific class without any styling which you will use as a selector. Dont know if it will work the way you want, but it looks like simplest solution to me... :)

stop propagation

$("#Submit").click(function(event){
  event.stopPropagation();

  if (typeof $_submitSend == "undefined")
      var $_submitSend = true;
  else if ($_submitSend == true)
      return false;

  $_submitSend = true;

  $(this).attr("disabled", "disabled");

  $(a_selector).load("Process.aspx?data=" + someDataObject, null, function(){
    alert("Done")});
    $_submitSend = false;
    $(this).removeAttr("disabled");
  }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM