Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
});  
like image 332
user2014429 Avatar asked Jul 06 '26 16:07

user2014429


1 Answers

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('');
    }
});
like image 107
Peter Rasmussen Avatar answered Jul 09 '26 04:07

Peter Rasmussen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!