2

What I am trying to achieve is something like this:

User clicks a button -> button becomes disabled (and a spinner appears on top) -> form is submitted.

I tried this and it works only sometimes (inside the HTML button):

onclick="
this.classList.toggle('button--loading'); // triggers spinner (created in CSS)
this.disabled=true; // disabled button
this.form.submit();" // submits form

Sometimes it works, sometimes it skips triggering the spinner and simply disables the button and submits afterwards. I am thinking that implementing a delay after the spinner is created will make it work 100% of the time, but I cannot figure it out.

Please note that I am quite a beginner with coding and really trying to find out how things work. Thanks!

pax_v
  • 25
  • 4
  • using the `onclick` like that will be a mess.. anyway you may try using `setTimeout` passing the code to perform as a callback. You can find lots of suggestions both on the `click` event and `setTimeout` here on SO – Diego D Feb 20 '23 at 11:19

1 Answers1

0

A couple of things:

Don't use inline HTML event attributes, like onclick - - this is a 25+ year old technique that won't die because people just keep copying and pasting other people's code. Instead use the modern API of .addEventListener().

Next, click is the wrong event to use with a form. You should be using submit on the form.

Lastly, to accomplish what you want, you'd need to cancel the native event within the submit handler, use a timer to cause a delay and then manually submit once the delay has passed.

Here's an example:

// Set up the event handler the correct way:
const form = document.querySelector("form");
form.addEventListener("submit", function(event){
  // Cancel the event
  event.preventDefault();
  
  document.querySelector("button").disabled = true;
  
  // Initiate a 3 second delay with a timer
  let timer = setTimeout(function(){
    // This function's code will run after the timer's delay
    // do watever you want here. This is just an example:
    alert("time's up!");
    
    // But, after that, manually subnit the form
    form.submit();
  }, 3000);
});
<form action="http://example.com" method="post">
  <button>Click to submit</button>
</form>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71