Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
Enable onclick event with JavaScript

I need to disable all buttons that match by class name and after the function runs, enable them back. I've tried the following but no luck.

let stb = document.getElementsByClassName("btn-st");

for (let i = 0; i < stb.length; i++) {
    stb.onclick = null;
}
// run some additional functions and enable

stb.onclick = true;

What am I missing?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You need to loop through stb again:

let stb = document.getElementsByClassName("btn-st");

for (let i = 0; i < stb.length; i++) {
    stb[i].onclick = null;
}
// run some additional functions and enable

for (let i = 0; i < stb.length; i++) {
    stb[i].onclick = true;
}

Keep in mind however that setting the onclick attribute to null won't disable the event (see @Jeremy Thille's comment).

If you want to disable a button, you should instead set its disabled property:

let stb = document.getElementsByClassName("btn-st");

for (let i = 0; i < stb.length; i++) {
    stb[i].disabled = true;
}
// run some additional functions and enable

for (let i = 0; i < stb.length; i++) {
    stb[i].disabled = false;
}
about 4 years ago · Juan Pablo Isaza Report

0

So the main two things that are missing is that the document.getElementsByClassName("btn-st"); returns an array so when you first go through and disable the .onclick you would have to do:

let stb = document.getElementsByClassName("btn-st");

for (let i = 0; i < stb.length; i++) {
    stb[i].onclick = null;
}

For the second portion, a couple people have mentioned that setting .onclick = true; doesn't really make sense, so instead you should set the onclick to an unnamed function with the following:

// run some additional functions and enable

for (let i = 0; i < stb.length; i++) {
    stb[i].onclick = function() {
        // do things when this button is clicked
    };
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!