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

140
Views
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 answers
Answer question

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 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!