0

I am currently making 5 buttons where after the user has pressed one of them, all get disabled. I have managed to do that, but I will also add a sign or colour of the selected button, but I can't get it to work. I have 5 of these buttons:

<button class="btn white black-text voteBtn" id="btn1" onclick=" disableButton();"> Button 1 </button>

and the javascript I use is:

 function disableButton(){
      var elems = document.getElementsByClassName("voteBtn");
      for(var i = 0; i < elems.length; i++) {
          elems[i].disabled = true;
      };                
};

I have tried using the toggle function to toggle an additional class and background colour from there, but I can't get it to work. Is there a way I can add a background colour to the selected button?

Sebastian
  • 27
  • 6
  • Are you talking about mutually exclusive buttons, meaning that one will always be enabled, but all the others won't? – Scott Marcus Apr 13 '20 at 19:23
  • https://stackoverflow.com/questions/14750078/style-disabled-button-with-css – epascarello Apr 13 '20 at 19:24
  • Also, [`getElementsByClassName()` should not be used (ever)](https://stackoverflow.com/questions/54952088/how-to-modify-style-to-html-elements-styled-externally-with-css-using-js/54952474#54952474), and very definitely not with loops. [Inline event handlers should also not be used.](https://stackoverflow.com/questions/43459890/javascript-function-doesnt-work-when-link-is-clicked/43459991#43459991) – Scott Marcus Apr 13 '20 at 19:25
  • @ScottMarcus What in the world are you talking about that getElementsByClassName should never be used..... – epascarello Apr 13 '20 at 19:31
  • @epascarello Read the link. – Scott Marcus Apr 13 '20 at 19:31
  • The OP is interacting (doesn't matter what you specifically do with the list) with the live node list returned by `getElementsByClassName()` in the loop, and that is a huge problem. – Scott Marcus Apr 13 '20 at 19:33
  • @ScottMarcus I meant that every button will be disabled after the user clicks one. So should I change getElementsByClassName to querySelector instead? Sorry for at the questions, but I am relativity new to javascript. – Sebastian Apr 13 '20 at 20:06
  • You should use `querySelectorAll()` instead of `getElementsByClassName()`. – Scott Marcus Apr 13 '20 at 20:08
  • ok, thank you for your help – Sebastian Apr 13 '20 at 20:11

1 Answers1

-1

If you want to change the background color of a button that is selected you should do this:

button#change:selected {
background-color: coral;
}

If you want to change the color on the click of the button do this:

function changeBackground() {
document.getElementById('button').style.backgroundColor = 'coral';
}