Jetoox Jetoox - 3 months ago 13
Ajax Question

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

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?

Answer

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