Filippo
Filippo

Reputation: 320

Javascript: disable submit button for X seconds

I would like to disable a submit button after it has been clicked. I.e. I do not want to call the function which is triggered by the click if I click within few seconds (3s in the example). I looked at this answer and tried to implement it on my code.

document.getElementById("butS").addEventListener("click",submit);
document.getElementById("butS").addEventListener("click",disableS);

   function disableS(){
      document.getElementById("butS").disabled = true;
      setTimeout(function(){document.getElementById("butS").disabled = false;},3000);
  }

I am not sure why it does not work. I am still able to click the button and trigger the function "submit". So I am wondering if the disable is actually disabling this string:

document.getElementById("butS").addEventListener("click",submit);

EDIT: I have not defined the button correctly. I had:

<a id="butS">Submit</a>

while I should have had:

<button id="butS">Submit</button>

Upvotes: 0

Views: 686

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65806

Your JavaScript is fine (aside from scanning the DOM over and over to get the button reference, which you only need to do once), but you may not be correctly referencing your HTML submit button. Make sure that your script is located just prior to your closing body tag so that by the time it is encountered, all the HTML will have been parsed into memory. If your script is running prior to the button being parsed, you won't get a reference to it.

As you can see here, as long as you reference the button correctly, your code works.

<!doctype html>
<html>
<head>
  <title></title>
</head>
<body>
  <button id="butS">Submit</button>

  <!-- By placing the script just before the closing of the body
       you ensure that all the DOM elements will have been parsed
       into memory and are accessible by the script. -->
  <script>
    // Just get the reference to your button one time
    // it's a waste to keep looking for the same element
    const button = document.getElementById("butS");
    button.addEventListener("click",submit);
    button.addEventListener("click",disableS);

    function disableS(){
      button.disabled = true;
      setTimeout(function(){ button.disabled = false; }, 3000);
    }

    function submit(){

    }
  </script>
</body>
</html>

Upvotes: 1

Related Questions