How to prevent form from submitting multiple times

2019-01-02 17:21发布

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

How to prevent this from happening?

21条回答
旧人旧事旧时光
2楼-- · 2019-01-02 17:43

Hash the current time, make it a hidden input on the form. On the server side, check the hash of each form submission; if you've already received that hash then you've got a repeat submission.

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.

查看更多
时光乱了年华
3楼-- · 2019-01-02 17:44

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>

查看更多
素衣白纱
4楼-- · 2019-01-02 17:45

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;

});
查看更多
临风纵饮
5楼-- · 2019-01-02 17:50

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.

查看更多
孤独总比滥情好
6楼-- · 2019-01-02 17:50

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);}
查看更多
伤终究还是伤i
7楼-- · 2019-01-02 17:51

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

查看更多
登录 后发表回答