4

Starting off with a simple form that requires an email address:

<form action="NextPage.php" method="post">
    <input type="email" name="contact[email]" required id="frmEmailA" autocomplete="email">
    <button type="submit">Submit</button>
</form>

(Non-essential features like labels and other fields have been removed for troubleshooting purposes.)

Some time ago, I was having trouble with double submission. I remember trying many different solutions, but the only one to work I found here.

So, I implemented that solution:

<form action="NextPage.php" method="post">
    <input type="email" name="contact[email]" required id="frmEmailA" autocomplete="email">
    <button type="submit" onclick="this.form.submit(); this.disabled = true;">Submit</button>
</form>

This was over a month ago, and I forgot all about it until just now. The "required" attribute now doesn't do anything as this.form.submit(); seems to override required.

A lot of the solutions to this problem require a lot of plugins or extra features, but is there an elegant solution?

The most elegant solution possible would be pure html, but I expect I'll need javascript also. I'd like to avoid downloading libraries or installing plugins if at all possible.

Examples:

All I want is a form that doesn't submit twice on double clicking, and honours the required attribute. Ideally without having to learn a new library or markup language. I wouldn't mind writing a couple of lengthy javascript functions if I needed to. Even a page that redirects to the next page wouldn't be too inelegant.

(I also know PHP and SQL, but I don't think either of them would help here.)

Is this even possible?

  • A down vote and no comment? I'm trying to write the best questions I can. If anyone has guidance on how to improve this one, or where the duplicates are, I would appreciate learning. – Jonathon Philip Chambers Sep 22 '18 at 08:46

2 Answers2

2

Instead of disabling the button in the onclick attribute of the button, disable it in the onsubmit attribute of the form.

You need to give the submit button a name, and then you can refer to it as this.<name> in the onsubmit attribute. Or you could give it an ID, then you could use document.getElementById("<id>") to refer to it.

<form action="NextPage.php" method="post" onsubmit="this.submitButton.disabled = true;">
  <input type="email" name="contact[email]" required id="frmEmailA" autocomplete="email">
  <button type="submit" name="submitButton">Submit</button>
</form>

The reason your code needed to call this.form.submit() is because clicking on a disabled button doesn't trigger the default form submission. But if you put the disabling code in the onsubmit attribute, it only runs once the form submission process has started.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

For jQuery fans:

$('form').submit(function(){
   $(':submit').attr('disabled','disabled');
});
Shadi Alnamrouti
  • 11,796
  • 4
  • 56
  • 54