0

I am trying to disable ALL buttons on an HTML page, then have them enabled again after x seconds (in the example it is 5 seconds.) The Button IDs are dynamically created and will change of page refresh so I am unable to use document.getElementById.

This code works will with selecting an ID but how can I have it select all buttons? If it helps, all buttons have the class "btn"

function submitPoll() {
    document.getElementById("votebutton112233").disabled = true;
    setTimeout(function() {
        document.getElementById("votebutton112233").disabled = false;
    }, 5000);
}
document.getElementById("votebutton112233").addEventListener("click", submitPoll);

Code that I have tried that does NOT work:

replacing the document.getElementById("votebutton") with

document.getElementsByClassName("btn")

or replacing it with document.getElementsByTagName('button')

jQuery is not preferred but I will use it if I must

  • Have a look at `setTimeout` - https://stackoverflow.com/questions/11901074/javascript-call-a-function-after-specific-time-period – Rylee Oct 15 '20 at 02:19

1 Answers1

1

Iterate over all elements that match the .btn selector string:

function submitPoll() {
  const btns = document.querySelectorAll('.btn');
  for (const btn of btns) {
    btn.disabled = true;
  }
  setTimeout(() => {
    for (const btn of btns) {
      btn.disabled = false;
    }
  }, 5000);
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320