Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda