Home > Software design >  Enable onclick event with JavaScript
Enable onclick event with JavaScript

Time:11-01

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?

CodePudding user response:

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
    };
}

CodePudding user response:

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;
}
  • Related