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
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.