Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

170
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda