0

So i need a button to get disabled after its clicked and then after few seconds it should become enabled again. I added a class button-disabled since i want to use it couple of times on the same page. Here is what i tried

$(document).on('click', '.button-disabled', function (){
                $(this).prop('disabled', true);
                setTimeout(function() {
                $(this).prop('disabled', false);
                }, 3500);
                }); 


<button type="button" id="buttonSettings" class="btn btn-success button-disabled">Sacuvaj</button>

I looked up similar questions on the site, but none of those help because everytime buttons does get disabled after click but it never gets enabled again. Any help would be appreciated.

Chilipepper
  • 172
  • 1
  • 11

2 Answers2

7

setTimeout is always executed in the global scope, as it's really window.setTimeout (or more accurately WindowTimers), so inside the callback this will be the window, not the element.

You have to store a reference to the element

$(document).on('click', '.button-disabled', function (){

      var element = $(this);

      element.prop('disabled', true);

      setTimeout(function() {

           console.log(this); // gives "window"

           element.prop('disabled', false);

      }, 3500);
}); 

As a sidenote, newer browsers accepts additional arguments in setTimeout so you could also do

setTimeout(function(element) {
    $(element).prop('disabled', false);
}, 3500, this);

or using bind()

setTimeout(function() {
    $(this).prop('disabled', false);
}.bind(this), 3500);
adeneo
  • 303,455
  • 27
  • 380
  • 377
1

Create an instance of this & use the instance to remove disable. Can try something like below.

$(document).on('click', '.button-disabled', function (){
     var self = $(this);
     $(this).prop('disabled', true);
     setTimeout(function() {
        $(self).removeAttr('disabled');
     }, 3500);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button type="button" id="buttonSettings" class="btn btn-success button-disabled">Sacuvaj</button>
MH2K9
  • 11,772
  • 7
  • 31
  • 48