2

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.

curious1
  • 14,155
  • 37
  • 130
  • 231
  • you can use $("form").submit(function(){e.preventDefaults()}); after your first submission – Andam May 14 '19 at 11:31
  • I think this is opinion-based or belongs to [codereview](https://codereview.stackexchange.com/) as it's not a problem and can be done in many ways. – DontVoteMeDown May 14 '19 at 11:33
  • Thanks for your input. Could you please show it in code? I tried that before, but didn't like the code ("after your first submission") in terms of clean code. – curious1 May 14 '19 at 11:33
  • 1
    If you set the button type propertie to `type="button"` it won't trigger the form. [This](https://stackoverflow.com/q/932653/9119186) might be helpfull – Vencovsky May 14 '19 at 11:40
  • Possible duplicate of [How to Prevent Users from Submitting a Form Twice](https://stackoverflow.com/questions/16814157/how-to-prevent-users-from-submitting-a-form-twice) (second answer) – vrintle May 14 '19 at 11:57

2 Answers2

0

You can use that method: event.preventDefault()

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

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
});
Deepak
  • 187
  • 1
  • 1
  • 10