How to prevent form from submitting multiple times from client side?

JavascriptSubmit

Javascript Problem Overview


Sometimes when the response is slow, one might click the submit button multiple times.

How to prevent this from happening?

Javascript Solutions


Solution 1 - Javascript

Use unobtrusive javascript to disable the submit event on the form after it has already been submitted. Here is an example using jQuery.

EDIT: Fixed issue with submitting a form without clicking the submit button. Thanks, ichiban.

$("body").on("submit", "form", function() {
    $(this).submit(function() {
        return false;
    });
    return true;
});

Solution 2 - Javascript

I tried vanstee's solution along with asp mvc 3 unobtrusive validation, and if client validation fails, code is still run, and form submit is disabled for good. I'm not able to resubmit after correcting fields. (see bjan's comment)

So I modified vanstee's script like this:

$("form").submit(function () {
    if ($(this).valid()) {
        $(this).submit(function () {
            return false;
        });
        return true;
    }
    else {
        return false;
    }
});

Solution 3 - Javascript

Client side form submission control can be achieved quite elegantly by having the onsubmit handler hide the submit button and replace it with a loading animation. That way the user gets immediate visual feedback in the same spot where his action (the click) happened. At the same time you prevent the form from being submitted another time.

If you submit the form via XHR keep in mind that you also have to handle submission errors, for example a timeout. You would have to display the submit button again because the user needs to resubmit the form.

On another note, llimllib brings up a very valid point. All form validation must happen server side. This includes multiple submission checks. Never trust the client! This is not only a case if javascript is disabled. You must keep in mind that all client side code can be modified. It is somewhat difficult to imagine but the html/javascript talking to your server is not necessarily the html/javascript you have written.

As llimllib suggests, generate the form with an identifier that is unique for that form and put it in a hidden input field. Store that identifier. When receiving form data only process it when the identifier matches. (Also linking the identifier to the users session and match that, as well, for extra security.) After the data processing delete the identifier.

Of course, once in a while, you'd need to clean up the identifiers for which never any form data was submitted. But most probably your website already employs some sort of "garbage collection" mechanism.

Solution 4 - Javascript

Here's simple way to do that:

<form onsubmit="return checkBeforeSubmit()">
  some input:<input type="text">
  <input type="submit" value="submit" />
</form>

<script type="text/javascript">
  var wasSubmitted = false;    
    function checkBeforeSubmit(){
      if(!wasSubmitted) {
        wasSubmitted = true;
        return wasSubmitted;
      }
      return false;
    }    
</script>

Solution 5 - Javascript

<form onsubmit="if(submitted) return false; submitted = true; return true">

Solution 6 - Javascript

The most simple answer to this question as asked: "Sometimes when the response is slow, one might click the submit button multiple times. How to prevent this from happening?"

Just Disable the form submit button, like below code.

<form ... onsubmit="buttonName.disabled=true; return true;">
  <input type="submit" name="buttonName" value="Submit">
</form>

It will disable the submit button, on first click for submitting. Also if you have some validation rules, then it will works fine. Hope it will help.

Solution 7 - Javascript

Create a unique identifier (for example, you can hash the current time), and make it a hidden input on the form. On the server side, check the unique identifier of each form submission; if you've already received that hash then you've got a repeat submission. The only way for the user to re-submit is to reload the form page.

edit: relying on javascript is not a good idea, so you all can keep upvoting those ideas but some users won't have it enabled. The correct answer is to not trust user input on the server side.

Solution 8 - Javascript

Disable the submit button soon after a click. Make sure you handle validations properly. Also keep an intermediate page for all processing or DB operations and then redirect to next page. THis makes sure that Refreshing the second page does not do another processing.

Solution 9 - Javascript

You could also display a progress bar or a spinner to indicate that the form is processing.

Solution 10 - Javascript

Using JQuery you can do:

$('input:submit').click( function() { this.disabled = true } );

&

   $('input:submit').keypress( function(e) {
     if (e.which == 13) {
        this.disabled = true 
     } 
    }
   );

Solution 11 - Javascript

I know you tagged your question with 'javascript' but here's a solution that do not depends on javascript at all:

It's a webapp pattern named PRG, and here's a good article that describes it

Solution 12 - Javascript

You can prevent multiple submit simply with :

var Workin = false;

$('form').submit(function()
{
   if(Workin) return false;
   Workin =true;

   // codes here.
   // Once you finish turn the Workin variable into false 
   // to enable the submit event again
   Workin = false;

});

Solution 13 - Javascript

On the client side, you should disable the submit button once the form is submitted with javascript code like as the method provided by @vanstee and @chaos.

But there is a problem for network lag or javascript-disabled situation where you shouldn't rely on the JS to prevent this from happening.

So, on the server-side, you should check the repeated submission from the same clients and omit the repeated one which seems a false attempt from the user.

Solution 14 - Javascript

You can try safeform jquery plugin.

$('#example').safeform({
    timeout: 5000, // disable form on 5 sec. after submit
    submit: function(event) {
        // put here validation and ajax stuff...

        // no need to wait for timeout, re-enable the form ASAP
        $(this).safeform('complete');
        return false;
    }
})

Solution 15 - Javascript

The simpliest and elegant solution for me:

function checkForm(form) // Submit button clicked
{
    form.myButton.disabled = true;
    form.myButton.value = "Please wait...";
    return true;
}

<form method="POST" action="..." onsubmit="return checkForm(this);">
    ...
    <input type="submit" name="myButton" value="Submit">
</form>

Link for more...

Solution 16 - Javascript

Use this code in your form.it will handle multiple clicks.

<script type="text/javascript">
    $(document).ready(function() {
	    $("form").submit(function() {
		    $(this).submit(function() {
		        return false;
		    });
		    return true;
	    }); 	
    }); 
</script>

it will work for sure.

Solution 17 - Javascript

This allow submit every 2 seconds. In case of front validation.

$(document).ready(function() {
    $('form[debounce]').submit(function(e) {
        const submiting = !!$(this).data('submiting');

        if(!submiting) {
            $(this).data('submiting', true);

            setTimeout(() => {
                $(this).data('submiting', false);
            }, 2000);

            return true;
        }

        e.preventDefault();
        return false;
    });
})

Solution 18 - Javascript

the best way to prevent multiple from submission is this just pass the button id in the method.

    function DisableButton() {
        document.getElementById("btnPostJob").disabled = true;
    }
    window.onbeforeunload = DisableButton; 

Solution 19 - Javascript

To do this using javascript is bit easy. Following is the code which will give desired functionality :

$('#disable').on('click', function(){
    $('#disable').attr("disabled", true);
  });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="disable">Disable Me!</button>

Solution 20 - Javascript

Most simple solutions is that disable the button on click, enable it after the operation completes. To check similar solution on jsfiddle :

[click here][1]

And you can find some other solution on this answer.

Solution 21 - Javascript

This works very fine for me. It submit the farm and make button disable and after 2 sec active the button.

<button id="submit" type="submit" onclick="submitLimit()">Yes</button>

function submitLimit() {
var btn = document.getElementById('submit')
setTimeout(function() {
    btn.setAttribute('disabled', 'disabled');
}, 1);

setTimeout(function() {
    btn.removeAttribute('disabled');
}, 2000);}

In ECMA6 Syntex

function submitLimit() {
submitBtn = document.getElementById('submit');

setTimeout(() => { submitBtn.setAttribute('disabled', 'disabled') }, 1);

setTimeout(() => { submitBtn.removeAttribute('disabled') }, 4000);}

Solution 22 - Javascript

Just to add to the possible answers without bypassing browser input validation

$( document ).ready(function() {
	$('.btn-submit').on('click', function() {
		if(this.form.checkValidity()) {
			$(this).attr("disabled", "disabled");
			$(this).val("Submitting...");
			this.form.submit();
		}
	});
});

Solution 23 - Javascript

An alternative to what was proposed before is:

jQuery('form').submit(function(){
     $(this).find(':submit').attr( 'disabled','disabled' );
     //the rest of your code
});

Solution 24 - Javascript

<h3>Form</h3>
<form action='' id='theform' >
<div class='row'>
    <div class="form-group col-md-4">
            <label for="name">Name:</label>
            <input type='text' name='name' class='form-control'/>
    </div>
</div>  
<div class='row'>
    <div class="form-group col-md-4">
            <label for="email">Email:</label>
            <input type='text' name='email' class='form-control'/>
    </div>
</div>  
<div class='row'>
    <div class="form-group col-md-4">
         <input class='btn btn-primary pull-right' type="button" value="Submit" id='btnsubmit' />   
    </div>
</div>
</form>



<script>

    $(function()
    {
      $('#btnsubmit').on('click',function()
      {
        $(this).val('Please wait ...')
          .attr('disabled','disabled');
        $('#theform').submit();
      });
      
    });

</script>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionomgView Question on Stackoverflow
Solution 1 - JavascriptvansteeView Answer on Stackoverflow
Solution 2 - Javascriptm irinaView Answer on Stackoverflow
Solution 3 - JavascriptRobView Answer on Stackoverflow
Solution 4 - JavascriptichibanView Answer on Stackoverflow
Solution 5 - JavascriptchaosView Answer on Stackoverflow
Solution 6 - JavascriptImran KhanView Answer on Stackoverflow
Solution 7 - JavascriptllimllibView Answer on Stackoverflow
Solution 8 - JavascriptShobanView Answer on Stackoverflow
Solution 9 - JavascriptTony BorfView Answer on Stackoverflow
Solution 10 - JavascriptBoris GuéryView Answer on Stackoverflow
Solution 11 - JavascriptPablo FernandezView Answer on Stackoverflow
Solution 12 - JavascriptAlphaView Answer on Stackoverflow
Solution 13 - JavascriptsteveyangView Answer on Stackoverflow
Solution 14 - JavascriptMax KamenkovView Answer on Stackoverflow
Solution 15 - JavascriptSolisView Answer on Stackoverflow
Solution 16 - JavascriptBachasView Answer on Stackoverflow
Solution 17 - JavascriptAurelView Answer on Stackoverflow
Solution 18 - Javascriptuser2427182View Answer on Stackoverflow
Solution 19 - JavascriptRishView Answer on Stackoverflow
Solution 20 - JavascriptKalyaniView Answer on Stackoverflow
Solution 21 - JavascriptAwais JameelView Answer on Stackoverflow
Solution 22 - JavascriptRoiView Answer on Stackoverflow
Solution 23 - JavascriptKisded Szabi - CodeRevolutionView Answer on Stackoverflow
Solution 24 - Javascriptdanish_waniView Answer on Stackoverflow