HTML change radio button background

Viewed 62

I would like the background color to remain the same foreach <ul> as lightgray.

Currently when clicking the radio button, it will change the ul background wrongly. I dont know how to make the jquery script loop thru all the ul available, I would really appreciate it if the script can be small, as this concept will be applied to 100+ ul

$(document).ready(function() {
   $("ul.options-list li").on("click",function() {
            if($(this).find('input[type="radio"]').is(':checked')) { 
          $('ul.options-list li').removeClass('change_color');
          $(this).addClass('change_color');
        }
    });
});
ul.options-list li.change_color{
        background-color: lightgray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  Q1
  <ul class="options-list">
    <li>
        <input type="radio" name="r1" id="1" value="1" data-toggle="radio">O1
    </li>
    <li>
        <input type="radio" name="r1" id="2" value="2" data-toggle="radio">O2
    </li>
  </ul>
</div>


<div>
  Q2
  <ul class="options-list">
    <li>
        <input type="radio" name="r2" id="3" value="3" data-toggle="radio">A1
    </li>
    <li>
        <input type="radio" name="r2" id="4" value="4" data-toggle="radio">A2
    </li>
  </ul>
</div>

2 Answers

You can loop through your ul li using each loop then use $(this) to check if the radio is checked depending on this add or remove your class.

Demo Code :

$(document).ready(function() {
  $("ul.options-list li").on("click", function() {
  //loop through ul li 
    $("ul.options-list li").each(function() {
      if ($(this).find('input[type="radio"]').is(':checked')) {
        $(this).addClass('change_color');//add change_Color
      } else {
        $(this).removeClass('change_color');//remove same
      }
    })
  });
});
ul.options-list li.change_color {
  background-color: lightgray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  Q1
  <ul class="options-list">
    <li>
      <input type="radio" name="r1" id="1" value="1" data-toggle="radio">O1
    </li>
    <li>
      <input type="radio" name="r1" id="2" value="2" data-toggle="radio">O2
    </li>
  </ul>
</div>


<div>
  Q2
  <ul class="options-list">
    <li>
      <input type="radio" name="r2" id="3" value="3" data-toggle="radio">A1
    </li>
    <li>
      <input type="radio" name="r2" id="4" value="4" data-toggle="radio">A2
    </li>
  </ul>
</div>

Related