curious1
curious1

Reputation: 14727

Disable buttons to avoid multiple form submission

I have a web form and I have noticed that it generates multiple submissions of the same data (spaced about 100 milliseconds). Based on my research, disabling buttons after form submission is one of a few things to do. I have the following two methods to disable form buttons:

Method 1:
$('form#my-form').submit(function(e) {
    $(this).find('button').prop("disabled",true);
    return true;
});

Method 2:
$('form#my-form').submit(function(e) {
    $(this).find('button').attr('onclick',"return false;");
});

Let's just focus on disabling buttons at form submission in the browser. Which method is better? Or other better ways? Any implications? I know that Method 1 is unable to pass to the backend the information of which button being clicked if a form has multiple buttons for different things.

Upvotes: 2

Views: 862

Answers (2)

Deepak
Deepak

Reputation: 197

Give it a try ,I think delay can make your work easy.

 $('#id').on('click',function(){
    // let a common class(disable-btn) for each button which should be disabled for on second
    $('.disable-btn').prop('disabled',true);
    setTimeout(function(){
       // enable click after 1 second
       $('.disable-btn').prop('disabled',false);
    },1000); // 1 second delay
});

Upvotes: 0

Evgeny Skarlat
Evgeny Skarlat

Reputation: 152

You can use that method: event.preventDefault()

$('form#my-form').submit(function(e) {
     e.preventDefault() 
     //do somethings
}

Upvotes: -1

Related Questions