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

145
Visualizações
How do i disable a button after i have clicked it 2 times?

I have a project for school, which consists of making a text editor. I added a menu button, which is supposed to be clicked and disabled after clicking it 2 times, so it wont append more and more childs of the menu button. Here is the code:

let btn = document.createElement('input');
btn.type = 'button';
btn.value = 'Open Menu';
btn.onclick = () => {
let btn2 = document.createElement('input');
btn2.type = 'button';
btn2.value = 'New Text';
document.body.appendChild(btn2);
}
document.body.appendChild(btn);

As you can see, i have a button that after it gets clicked, appends a new button to the body of the document. And if you click it 2 or 3 times, 3 new buttons gets appended, which is buggy. I tried adding a counter like this:

let counter = 0;
if (counter === 2) {
document.querySelector("button")[0].disabled = "disabled"; || document.querySelector("button")[0].disabled = true;
}

Well, that didn't seem to work out as expected. Any ideas on how to get this working? Thank you

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You should initialize the counter outside of the onclick event handler. Then you can add this code in the end of onclick event handler:

counter++;
if (counter === 2) btn.disabled = true;

const btn = document.createElement('input');
let counter = 0;
btn.type = 'button';
btn.value = 'Open Menu';
btn.onclick = () => {
  let btn2 = document.createElement('input');
  btn2.type = 'button';
  btn2.value = 'New Text';
  document.body.appendChild(btn2);
  counter++;
  if (counter === 2) btn.disabled = true;
}
document.body.appendChild(btn);

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