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
  • 182
  • 1
  • 12

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
  • 312,895
  • 29
  • 395
  • 388
  • As far as I know your last paragraph is incorrect -- although arguments can be passed to the callback this way, `this` cannot be bound by passing it. – Frédéric Hamidi Dec 26 '14 at 12:25
  • @FrédéricHamidi - just a typo, was supposed to use the argument instead. – adeneo Dec 26 '14 at 12:28
  • So what would passing `this` to `setTimeout()` achieve, then? :) – Frédéric Hamidi Dec 26 '14 at 12:29
  • It's just another way to lock in the value of `this` by passing it instead of using a variable. Of course `bind` could be used as well, but I don't really like that approach. – adeneo Dec 26 '14 at 12:30
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,951
  • 7
  • 32
  • 49