0

I have added the below onclick code to the submit button in order to prevent users from submitting several times by clicking quickly on the button.

<button type="submit" onclick="this.disabled=true;this.value='Sending, please wait...';this.form.submit();" class="btn btn-primary" align="right">Submit</button>

After doing this addition, I noticed that the button is submitting two times instead of once. How can I fix this ?

v4valve
  • 49
  • 7

4 Answers4

3

Extending @Nico_ 's answer, one option would be to change the button type to type="button" and it would submit only when you decide to submit the function.

The other option would be to assign a JS function instead of doing everything in onclick.

An example could be:

<button id="button1" type="submit" onclick="submitAction(event)">

<script>
function submitAction(e) {
   e.preventDefault();
   document.getElementById("button1").disabled = true;
   document.getElementById("button1").value = 'Sending, please wait...';
   this.form.submit();
}
</script>
Mihail Minkov
  • 2,463
  • 2
  • 24
  • 41
  • I based my answer on this: https://stackoverflow.com/questions/8614438/access-event-to-call-preventdefault-from-custom-function-originating-from-onclic – Mihail Minkov Dec 02 '19 at 18:36
1

It's because your button has a type "submit" so if the user press it, whatever is your onclick, the form will be submited since your onclick do that too, the form is submited twice. You can fix that by removing the type.

Nico_
  • 1,388
  • 17
  • 31
1

Either add return false; at the end of your inline Javascript event listener:

<button type="submit" 
  onclick="this.disabled=true; this.value='Sending, please wait...'; this.form.submit(); return false;" class="btn btn-primary" align="right">Submit</button>

or simply omit this.form.submit(); (because that is what a submit button already does by itself when clicked):

<button type="submit" 
  onclick="this.disabled=true; this.value='Sending, please wait...';" class="btn btn-primary" align="right">Submit</button>
connexo
  • 53,704
  • 14
  • 91
  • 128
0

I would suggest you to disable the button by adding a disabled attribute to it once the user has submitted the form.

You can submit a form using javascript using form.submit();. This way you can remove type="submit" and allows you to have more freedom in controlling the behaviour of onClick event.

For example:

function myFunction() {
  document.getElementById("myBtn").disabled = true;
}
<button id="myBtn"onclick="myFunction()">Clickable once only.</button>