Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable the submit button after clicking and enable it back again after a few seconds

Tags:

I'm using jquery $.post when submitting a form. I want to disable the button for like 5 seconds after it has been clicked to avoid multiple submission of the form.

here's what I've done for now:

$('#btn').click(function(){     $.post(base_url + 'folder/controller/function',$('#formID').serialize(),function(data){         $('#message').slideDown().html('<span>'+data+'</span>');     }); }); 

I've used fadeIn and fadeOut before, but still it doesn't work when I tested it clicking the button rapidly. What should I do to achieve what I wanted to happen?

like image 377
Jetoox Avatar asked Jun 07 '12 13:06

Jetoox


People also ask

How do you disable the submit button after clicking it?

1.1 To disable a submit button, you just need to add a disabled attribute to the submit button. $("#btnSubmit"). attr("disabled", true); 1.2 To enable a disabled button, set the disabled attribute to false, or remove the disabled attribute.

How do you disable a button for 30 seconds?

Here use setTimeout, to enable it after 30 seconds. In the anonymus function of setTimeout. Modify the DOM property is also called disabled and is a boolean that takes true or false.

How do I enable a submit button?

Approach: To enable or disable the form submit button, we use the below code snippet. $('#enabled'). click(function () { if ($('#submit-button').is(':disabled')) { $('#submit-button'). removeAttr('disabled'); } else { $('#submit-button').

How do you disable submit button until checkbox is checked?

When you click on checkbox .is(":checked") return true if it is checked other wise return false. According to selection of your checkbox button it will enable/disable button.


1 Answers

You can do what you wanted like this:

var fewSeconds = 5; $('#btn').click(function(){     // Ajax request     var btn = $(this);     btn.prop('disabled', true);     setTimeout(function(){         btn.prop('disabled', false);     }, fewSeconds*1000); }); 

or you can use jQuery's .complete() method which is being executed after the ajax receives a response:

$('#btn').click(function(){     var btn = $(this);     $.post(/*...*/).complete(function(){         btn.prop('disabled', false);     });     btn.prop('disabled', true);  }); 

edit: this is an example with 3 seconds server-side response delay


Edit

Since even the answer is 8 years old, but still getting attention and jQuery is getting less popular I think it's worth adding example without jQuery

const fewSeconds = 3   document.querySelector('#btn').addEventListener('click', (e) => {     e.target.disabled = true   setTimeout(() => {    e.target.disabled = false   }, fewSeconds * 1000) })
<input type='button' id="btn" value="click me" />
like image 119
Teneff Avatar answered Oct 13 '22 10:10

Teneff