user2014429
user2014429

Reputation: 2567

disable button with timeout

I have this form with conditions that alert validation errors before posting data. the problem is if someone double clicks (by mistake perhaps), the form is submitted, then the form is cleared on the first click then the second click will alert 'form empty', which could be confusing as it all happens in a split second. so what I want is to temporarily disable the button when clicked for 3 seconds. but what I have now just times out the whole function for 3 seconds not just disabling the button. how should I be doing this? here is a simplified version of the form. Thanks

$('#send').click(function(){

   var self = $('#send');
       setTimeout(function() {
       self.disabled = false;
   if(!$('#text').val()){
      alert('field empty');
  }else{
        $('#message').html('done');
        $('#text').val('');
    }
  }, 3000);
});  

Upvotes: 2

Views: 14391

Answers (3)

Peter Rasmussen
Peter Rasmussen

Reputation: 16922

I've written a small example for you, of disabling a button on click. The timeout will enable the button after 3000 miliseconds.

Working demo

html:

<input id="text">
<input id="send" type="button" value="send"/>
<div id="message"></div>

Javascript:

$('#send').click(function(){
    var button = $(this);
    button.attr('disabled', 'disabled');
    setTimeout(function() {
         button.removeAttr('disabled');
    },3000);
    if(!$('#text').val()){
       alert('field empty');
       button.removeAttr('disabled');
    }else{
        $('#message').html('done');
        $('#text').val('');
    }
});

Upvotes: 8

John S
John S

Reputation: 21482

You are not correctly disabling the button. You are setting the .disabled property on a jQuery object, not the wrapped DOM element.

Try:

self.prop('disabled', false);

Instead of:

self.disabled = false;

EDIT:

Actually the code above was attempting to re-ebable the button. There was no code to disable the button.

I also think you want to perform the validation right away. The call to setTimeout() should just be for re-enabling the button, like this:

$('#send').click(function() {
    var self = $(this);

    // Disable the button.
    self.prop('disabled', true);

    // Process click.
    if (!$('#text').val()) {
        alert('field empty');
    } else {
        $('#message').html('done');
        $('#text').val('');
    }

    // Cause the button to re-enable after 3 seconds.
    setTimeout(function() {
        self.prop('disabled', false);
    }, 3000);
});

Upvotes: 2

Marcus
Marcus

Reputation: 5447

You could use jQuery's one() instead of click(). Once the function is run it will be unbound.
If you want to re-enable it you could put the timeout to re-bind it at the end of the function.

Using your method, it looks like you're never actually disabling the button:

this.disabled = 'disabled';

Upvotes: 2

Related Questions