'How to prevent HTML forms being sent multiple times in a row within a short time period?

I'm using this simple form to implement a login:

<form action="/handleLogin/" name="login" method="post">
    <div>
        <label for="userid">Username</label>
        <input type="text" id="userid" name="identifier" value="" pattern="\s*([^@\s]+@[^@\s]+|\d+)\s*" data-parsley-required>
    </div>
    <div>
        <label for="userpassword">Password</label>
        <input type="password" id="userpassword" name="credential" data-parsley-required>
    </div>
    <button id="login-button" class="button" type="submit">Login</button>
</form>

Our QA team noticed that it's possible to click the login-button twice or hammer the return button on the keyboard two times in a row within a short period of time.

This leads to multiple requests being sent to the server which causes problems.

Thus, I tried to prevent this with the following JavaScript code:

$('form[name="login"]').on('submit', function() {
    $("#userid, #userpassword, #login-button").attr("disabled", true);
});

Unfortunately, now the values of username + password won't be sent to the server anymore. I guess that's because they're disabled and the browsers thinks: "Ok, if the fields are disabled, I'm not gonna send em".

How can I work around this problem?

I thought about canceling the original submit event using "return false;" and manually send a copy of the form but that's not really a very good solution, I think.



Solution 1:[1]

Try this:

$('form[name="login"]').on('submit', function() {
   $("#login-button").attr("disabled", true);
   $("#userid, #userpassword").attr("readonly", true);
});

Solution 2:[2]

Use

$('button[type=submit], input[type=submit]').prop('disabled',true);

instead of:

$("#userid, #userpassword, #login-button").attr("disabled", true);

It will only disable button.

Demo Link

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anton Zikov
Solution 2 Glorfindel