Home > Software design >  Add class when Checkbox checked OR value not equals "0" in Selected Option
Add class when Checkbox checked OR value not equals "0" in Selected Option

Time:10-26

I have a filter that has several checkboxes and a dropdown.

<input type="checkbox" id="myCheck1">
<input type="checkbox" id="myCheck2">

<select id="mySelect">
  <option value>Zero</option>
  <option value="one">One</option>
  <option value="two">Two</option>
  <option value-"three">Three</option>
</select>

I need to notify the user that a filter is enabled. Minimal to add a class to html if any of the the checkboxes is checked, or(!) the value in the <select> is not zero.

I figured out how to add a class separately for each event.

let someCheckbox1 = document.getElementById('myCheck1');
someCheckbox1.addEventListener('change', e => {
  if(e.target.checked === true) {
    document.getElementById('alert').classList.add('red');
  }
  if(e.target.checked === false) {
    document.getElementById('alert').classList.remove('red');
  }
});

let someCheckbox2 = document.getElementById('myCheck2');
someCheckbox2.addEventListener('change', e => {
  if(e.target.checked === true) {
    document.getElementById('alert').classList.add('red');
  }
  if(e.target.checked === false) {
    document.getElementById('alert').classList.remove('red');
  }
});

let someSelect = document.getElementById('mySelect')
someSelect.addEventListener('change', function() {
  var index = someSelect.selectedIndex;
  if (index != 0) {
    document.getElementById('alert').classList.add('red');
  }
  if (index == 0) {
    document.getElementById('alert').classList.remove('red');
  }
})

In this version, if you first select an element from the list or check one of the checkboxes, and then check and reset another checkbox, the class will be removed, but the value in the or first checkbox will still be active. This does not fit. How to make the class to be added in any case if at least one of the elements was clicked (checkbox or select).

Thank you in advance!

CodePudding user response:

Put the code that sets the class into a function, and call that from all the event listeners. It can check the status of both checkboxes and the dropdown.

let someCheckbox1 = document.getElementById('myCheck1');
let someCheckbox2 = document.getElementById('myCheck2');
let someSelect = document.getElementById('mySelect');

function toggleAlert() {
  document.getElementById('alert').classList.toggle("red", someCheckbox1.checked || someCheckbox2.checked || someSelect.value);
}

[someCheckbox1, someCheckbox2, someSelect].forEach(el => el.addEventListener('change', toggleAlert));
.red {
  color: red;
}
<input type="checkbox" id="myCheck1">
<input type="checkbox" id="myCheck2">

<select id="mySelect">
  <option value>Zero</option>
  <option value="one">One</option>
  <option value="two">Two</option>
  <option value- "three">Three</option>
</select>
<div id="alert">Alert</div>

  • Related