Melbin Mathai Melbin Mathai - 3 months ago 10
CSS Question

How to change the Color of the button When click the Checkbox

Here, there is a button and two more check boxes are added. I am trying to do is, when I click on any check box, the Button color should change to green or any other color. If I unchecked all the boxes, the button color should change to gray color. Please help me. Thank you.



.input {
font-weight: bold;
border-radius: 1px;
background-color: grey;
}

<input id="input" class="" value=" ... " type="button">

<input type="checkbox" class="check-box">
<input type="checkbox" class="check-box">
<input type="checkbox" class="check-box">




Answer

var elems = document.querySelectorAll('.check-box');
var btn = document.querySelector('.btn-elem');
[].forEach.call(elems, function(el) {
  el.addEventListener('change', function() {
    var checked = document.querySelectorAll('.check-box:checked');
    if (checked.length) {
      btn.style.backgroundColor = 'green';
    } else {
      btn.style.backgroundColor = '';
    }
  });
});
<input class="btn-elem" value="  ...  " style="font-weight: bold; border-radius: 1px; background-color: grey;" type="button">

<input type="checkbox" class="check-box">
<input type="checkbox" class="check-box">
<input type="checkbox" class="check-box">