Delay Button Submit Javascript

Viewed 143

I'm trying to add adelay on my submit button in javascript. But it just seems to freeze and no longer commits any action after clicking on it. Does anyone have an explanation ?

function Progress() {
   var button = document.getElementById("Button");
   var form = document.getElementById("new_video")

    form.onsubmit = function() {
      return false;
    }
    button.onclick = function() {
     setTimeout(function() {
        form.submit();
     }, 2000);
       return false;
    }
  }
<input type="submit" name="commit" value="Upload" class="btn btn btn-primary" onclick="Progress()" id="Button" data-disable-with="Upload" disabled="">
2 Answers

// Cache your Form Elements
const EL_form = document.querySelector("#myForm");
const EL_formSubmitBtn = EL_form.querySelector("#Button");

const Progress = (evt) => {
  evt.preventDefault(); // Prevent Browser Submit action
  
  EL_formSubmitBtn.disabled = true; // Disable the submit button
  
  setTimeout(function() {
    EL_form.submit(); // Or do AJAX stuff here
    EL_formSubmitBtn.disabled = false; // Enable the submit button
  }, 2000);
};


// Use Element.addEventListener instead of inline JS
// Don't attach handlers to button, rather use the Form "submit" Event:
EL_form.addEventListener("submit", Progress);
<form id="myForm" action="demo.php">
  <input id="Button" type="submit" value="Upload" class="btn btn btn-primary">
</form>

PS: Don't capitalise names of regular functions that do not actually return an Object - or are not a Class by definition, use rather progress as your function name. Or rather be more descriptive, it's actually a formSubmitHandler

You could try this:

var button = document.getElementById("Button");
var form = document.getElementById("new_video");

button.onclick = function(event) {
  event.preventDefault();
  setTimeout(form.submit, 2000);
}

and

<input type="submit" name="commit" value="Upload" class="btn btn btn-primary" id="Button" data-disable-with="Upload">

Hope this helps.

Related