Skip to content
Advertisement

Javascript to change of a list items color when checked

window.onchange  = function() {
  var ul = document.getElementById("list_id");
  var items = ul.getElementsByTagName("label");
  for (var i = 0; i < items.length; ++i) {
      if (items[i].checked = true){
         items[i].style.color = "red";
       };
  };
}
 <ul id="list_id" style="border: 1px solid rgb(51, 51, 51); padding: 10px; max-height: 
     250px; display: block; width: 25%; overflow-y: auto;">
  
  <li class="member user_1">
    <label class="checkbox" for="user_1">
      <input name="user[1]" type="hidden" value="0">
      <input id="user_1" name="user[1]" type="checkbox" value="1">
      One, User 
    </label>
  </li>

  <li class="member user_2">
    <label class="checkbox" for="user_440">
      <input name="user[2]" type="hidden" value="0">
      <input id="user_2" name="user[2]" type="checkbox" value="1">
      Two, User
    </label>
  </li>

</ul>

I am trying to write Javascript so that when one of these list items is selected by the user, the color changes red just for the selected item. The issue I am running into is that this selects all of the list items, instead of the one that is selected.

Right now my Javascript looks like this:

window.onchange  = function() {
  var ul = document.getElementById("list_id");
  var items = ul.getElementsByTagName("label");
  for (var i = 0; i < items.length; ++i) {
      if (items[i].checked = true){
         items[i].style.color = "red";
       };
    };

The HTML looks like this;

     <ul id="list_id" style="border: 1px solid rgb(51, 51, 51); padding: 10px; max-height: 
     250px; display: block; width: 25%; overflow-y: auto;">
  
    <li class="member user_1">
      <label class="checkbox" for="user_1">
        <input name="user[1]" type="hidden" value="0">
        <input id="user_1" name="user[1]" type="checkbox" value="1">
        One, User 
      </label>
    </li>
  
    <li class="member user_2">
      <label class="checkbox" for="user_440">
        <input name="user[2]" type="hidden" value="0">
        <input id="user_2" name="user[2]" type="checkbox" value="1">
        Two, User
      </label>
    </li>

   </ul>

Thanks for the help!

Advertisement

Answer

You can do something like this to achieve the desired result just what @HereticMonkey wrote in the comments.

[...document.querySelectorAll('label')].forEach(label => {
  label.addEventListener('change', () => {
    label.style.color = label.querySelector('[type="checkbox"]').checked ? "red" : "";
  });
});
<ul>
  <li>
    <label>
      <input type="checkbox">
      One, User 
    </label>
  </li>
  <li>
    <label>
      <input type="checkbox">
      Two, User
    </label>
  </li>
</ul>

Also check out this cool fiddle from @DavidsaysreinstateMonica

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement