9

i want to disable a button for a specific time. how can i do that?

maztt
  • 12,278
  • 21
  • 78
  • 153

4 Answers4

10

Since this is likely to be a task you might like to repeat, I think the best way to do this would be to extend jQuery like so:

$.fn.timedDisable = function(time) {
    if (time == null) { time = 5000; }
    return $(this).each(function() {
        $(this).attr('disabled', 'disabled');
        var disabledElem = $(this);
        setTimeout(function() {
            disabledElem.removeAttr('disabled');
        }, time);
    });
};

This will allow you to call a function on a set of matched elements which will temporarily disable them. As it is written, you can simply call the function, and the selected elements will be disabled for 5 seconds. You would do that like so:

$('#some-button').timedDisable();

You can adjust the default time setting by changing the 5000 in the following line:

if (time == null) { time = 5000; }

You can optionally pass in a time value in milliseconds to control how long the elements will be disabled for. For example:

$('#some-button').timedDisable(1000);

Here's a working demo: http://jsfiddle.net/fG2ES/

Ender
  • 14,995
  • 8
  • 36
  • 51
9

Disable the button and then use setTimeout to run a function that enables the button after a few seconds.

$('#some-button').attr("disabled", "disabled");
setTimeout('enableButton()', 5000);

function enableButton(){
   $('#some-button').removeAttr('disabled');
}
nc3b
  • 15,562
  • 5
  • 51
  • 63
  • This doesn't work: http://jsfiddle.net/RPQmM/ I believe the setTimeout is called wrong. – Ender Sep 06 '10 at 09:12
  • 2
    @Ender It does not work because your `enableButton` function is not in global scope which is required by the *way* `setTimeout` is being called. See this: http://jsfiddle.net/RPQmM/1/ – sharat87 Sep 06 '10 at 10:21
2

Try this.

(function(){
$('button').on('click',function(){
var $this=$(this);
        $this
            .attr('disabled','disabled');
             setTimeout(function() {
             $this.removeAttr('disabled');
             }, 3000);
      });
 })();

You can find a working example here http://jsfiddle.net/informativejavascript/AMqb5/

kamal
  • 149
  • 6
1

Might not be the most elegant solution, but I thought I'd play with jQuery queues on this one...

​$.fn.disableFor = function (time) {
    var el = this, qname = 'disqueue';
    el.queue(qname, function () {
        el.attr('disabled', 'disabled');
        setTimeout( function () {
            el.dequeue(qname);
        }, time || 3000);
    })
    .queue(qname, function () {
        el.removeAttr('disabled');
    })
    .dequeue(qname);
};

$('#btn').click( function () {
    ​$(this).disableFor(2000);​​​​
});

​ This is where I worked it out... http://jsfiddle.net/T9QJM/

And, for reference, How do I chain or queue custom functions using JQuery?

Community
  • 1
  • 1
sharat87
  • 7,330
  • 12
  • 55
  • 80