Site icon Cody Paste

Disable the button when the form is submitted

Solution:

  1. Disable the button when the form is submitted.
  2. Re-enable the button after the page is loaded or when the form submission is complete.

Example Implementation:

HTML:

JavaScript/jQuery:

Explanation:

  1. Disabling the Submit Button on Form Submission:
    • When the form is submitted ($('#myForm').submit()), we disable the submit button immediately ($('#submitButton').prop('disabled', true);) to prevent further clicks.
  2. Changing the Button Text:
    • Optionally, you can change the button text to “Submitting…” or something else to give feedback to the user that the form is being processed.
  3. Re-enabling the Button After Submission (Using Ajax):
    • If you’re using Ajax, you can re-enable the button when the submission is successful or if there’s an error by placing the code $('#submitButton').prop('disabled', false); in the success/error callbacks.
  4. Disabling the Button on Page Reload or Unload:
    • $(window).on('beforeunload', function() {...}): This disables the button if the page is being unloaded, which could happen when the user reloads or navigates away while the form is submitting. This will prevent the form from being accidentally submitted multiple times due to a page reload.

Additional Notes:

Exit mobile version